环境:PHP 5.3.5 MySQL Server 5.5.8,jquery 1.6版
使用 Ajax 自动填充国家的下拉列表。
我不断收到此错误,并且尝试了很多方法。例如在编码之前用“'$results'”包围$results。错误仍然存在。
这是一个输出示例:
array(1) {
[0]=>
array(4) {
["id"]=>
string(2) "45"
[0]=>
string(2) "45"
["nicename"]=>
string(16) "Christmas Island"
[1]=>
string(16) "Christmas Island"
}
}
这是ajax(我什至尝试将成功更改为完成-如果我这样做,错误代码就会重复。
$.ajax({
type: "POST",
url: "models/ajaxHandler.php",
data: {handler:"getCountries", nli:"-1"},
dataType: "json",
success: function(results){
//results = $.parseJSON(results);
var resultStr = "";
for(var x in results)
resultStr = resultStr + results[x];
alert("RESULT" + resultStr);
//populateDropDown(results);
},
error: function(xhr, status, error){
alert(xhr+ "| ajax failure: could not populate list of countires | " + status + " | error:" + error);
var xhrStr = "";
for(var x in xhr)
xhrStr = xhrStr + xhr[x];
alert(xhrStr);
}
});
在我对 php 中的 json 字符串进行编码后,我正在转义特殊字符,如下所示:
if (!empty($results)){
$json = json_encode($results);
//$json = form_safe_json($json);
echo $json;
}
function form_safe_json($json) {
$json = empty($json) ? '[]' : $json ;
$search = array('\\',"\n","\r","\f","\t","\b","'") ;
$replace = array('\\\\',"\\n", "\\r","\\f","\\t","\\b", "\'");
$json = str_replace($search,$replace,$json);
return $json;
}