AJAX request returning unicode characters as question marks

梦想的初衷 提交于 2020-02-01 08:16:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!