Solving this issue of sending arabic characters us

2020-03-03 05:41发布

问题:

I'm using an AJAX form in order to send data to another page named 'show.php'. Here is the source of pages:

form.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="ajaxsbmt.js" type="text/javascript"></script>
</head>
<div id="MyResult"></div>
    <form method="POST" action="response_norma.php" name="MyForm" onsubmit="xmlhttpPost('show.php', 'MyForm', 'MyResult', '<img src=\'indicator.gif\'>'); return false;">
      <input type="text" name="mytext" size="20">
      <input type="submit" value="Submit" name="ok">
    </form>
</body>
</html>

show.php

<?php
  echo $_REQUEST['mytext'];
?>

ajaxsbmt.js

function xmlhttpPost(strURL, formname, responsediv, responsemsg) {
  var xmlHttpReq = false;
  var self = this;
  // xhr for Mozilla/Safari/Ie7
  if (window.XMLHttpRequest) {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // xhr for all other versions of IE
  else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  self.xmlHttpReq.open('POST', strURL, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlHttpReq.onreadystatechange = function() {
    if (self.xmlHttpReq.readyState == 4) {
      // When ready, put the response into the form
      updatepage(self.xmlHttpReq.responseText, responsediv);
    } else {
      // While waiting for the respnse, display a message
      updatepage(responsemsg, responsediv);
    }
  }
  self.xmlHttpReq.send(getquerystring(formname));
}


function getquerystring(formname) {
  var form = document.forms[formname];
  var qstr = "";

  function GetElemValue(name, value) {
    qstr += (qstr.length > 0 ? "&" : "")
            + escape(name).replace(/\+/g, "%2B")
            + "="
            + escape(value ? value : "").replace(/\+/g, "%2B");
            ´//+ escape(value ? value : "").replace(/\n/g, "%0D");
  }

  var elemArray = form.elements;
  for (var i = 0; i < elemArray.length; i++) {
    var element = elemArray[i];
    var elemType = element.type.toUpperCase();
    var elemName = element.name;
    if (elemName) {
      if (
           elemType == "TEXT" 
        || elemType == "TEXTAREA" 
        || elemType == "PASSWORD" 
        || elemType == "BUTTON" 
        || elemType == "RESET" 
        || elemType == "SUBMIT" 
        || elemType == "FILE" 
        || elemType == "IMAGE" 
        || elemType == "HIDDEN"
      ) 
        GetElemValue(elemName, element.value);
      else if (elemType == "CHECKBOX" && element.checked) 
        GetElemValue(elemName, element.value ? element.value : "On");
      else if (elemType == "RADIO" && element.checked) 
        GetElemValue(elemName, element.value);
      else if (elemType.indexOf("SELECT") != -1)
        for (var j = 0; j < element.options.length; j++) {
          var option = element.options[j];
          if (option.selected) 
            GetElemValue(elemName, option.value ? option.value : option.text);
        }
    }
  }
  return qstr;
}

function updatepage(str, responsediv) {
  document.getElementById(responsediv).innerHTML = str;
}

PROBLEM

When I type English characters in the filed, data transfer successfully and I receive them top of the form.

But when I try to type Arabic characters, I receive another data, something like encoded words. e.g: %u0633%u0644%u0627%u0645. %u0686%u0637%u0648%u0631%u06CC instead of:
سلام. چطوری (if you have font.)

How can I solve this problem?

回答1:

You're using escape() and some fancy custom replacements. Don't do this.

escape() is broken and there is very little reason to use it.

The function you're looking for is called encodeURIComponent().

// use an array to hold the query string parts
var qstr = [];

qstr.appendParam = function(name, value) {
  this.push( 
     encodeURIComponent(name) 
     + (value > "" ? "=" + encodeURIComponent(value) : "")
  );
  return this;
}
qstr.toString = function () {
  return "?" + this.join("&");
}

// use like this:
qstr.appendParam("foo", "bar");
qstr.appendParam("arabic", "سلام. چطوری");

// now make a real query string.
qstr.toString() // "?foo=bar&arabic=%D8%B3%D9%84%D8%A7%D9%85.%20%DA%86%D8%B7%D9%88%D8%B1%DB%8C"

The above should replace your GetElemValue() function. Note how you can tweak objects by adding functions you need (like appendParam()) or overriding functions that are already there (like toString()).

Also note that you can return the array itself from your function getquerystring(). JavaScript calls toString() automatically in situations like this:

var url = "http://bla/" + qstr

Since toString() is overridden, the right thing will happen.



回答2:

<?php
  $orignialmytext = $_REQUEST['mytext'];
  $decodedmytext = urldecode($orignialmytext);
  echo $decodedmytext;
?>


回答3:

What is happening here is your page is encoding the characters as unicode. For example, %u0633 is the first character in your string. That is normal, though I am surprised it is happening automatically.

Now, you need to decode them when displaying to the viewer.

It looks like this may be what you want: http://www.php.net/manual/en/function.utf8-decode.php

string utf8_decode ( string $data )

That function takes encoded input, which looks like "%u0079" or "%u0078" and turns it back into letters. When you try to display the string using PHP, wrap it in:

utf8decode("mystring")

I think show.php should look like:

<?php
  echo utf8decode($_REQUEST['mytext']);
?>


回答4:

I think this may help:

self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

The above code should set the character set of the AJAX Request to UTF-8.