问题
I have the following PHP script being called by AJAX:
<?php
// file /ajax/loopback.php
$fp = fopen("php://input","r");
$pdt = "";
while(!feof($fp)) $pdt .= fgets($fp);
fclose($fp);
$_POST = json_decode($pdt,true);
if( !$_POST) $_POST = Array();
var_dump($_POST);
exit;
?>
I then call this script with the following JavaScript:
AJAX = function(url,data,callback) {
var a = new XMLHttpRequest();
if( data) {
data = JSON.stringify(data);
}
a.open("POST","/ajax/"+url,true);
a.onreadystatechange = function() {
if( a.readyState == 4) {
if( a.status == 200) {
callback(JSON.parse(a.responseText));
}
}
};
a.setRequestHeader("Content-Type","application/json");
a.send(data);
};
AJAX("loopback.php",{name:'ヴィックサ'},alert);
The expected result is an alert box containing:
Array(1) {
["name"]=>
string(5) "ヴィックサ"
}
(or maybe "string(10)" due to multibyte characters) But the result I'm getting is:
Array(1) {
["name"]=>
string(5) "?????"
}
What am I missing to allow Unicode characters to be passed via AJAX?
EDIT: I've added some code to show me what the raw post data is, and it seems like the ????? is there in the raw post data, ie. the Unicode isn't even making it to the server.
回答1:
On your page that has the JavaScript (or that is loading the JavaScript file) are you setting the charset to UTF-8?
header('Content-Type:text/html; charset=UTF-8');
Try looking at your script in Firebug, and make sure the characters in this line...
AJAX("loopback.php",{name:'ヴィックサ'},alert);
look the same in your source file as they do in the debugger.
( at least, I tried your script and it worked fine for me as soon as I set the character encoding. )
来源:https://stackoverflow.com/questions/8774959/ajax-request-returning-unicode-characters-as-question-marks