我正在从php向jquery发送JSON响应:
foreach ( $obj as $o )
{
$a[ $o->key] = utf8_encode($o->id);
}
die(json_encode($a));
我的html / jquery代码是:
$.ajax({
type:'POST',
url: "imoveis/carrega_bairros",
data: ({cidade:10}),
dataType:"json",
success: function(ret)
{ alert(ret)
if(ret.success)
{
// ...
}
else
alert("error");
}
});
json响应是完美的(我在控制台上得到它),但是jquery正在接收一个NULL ret对象,它会警告“错误”。有什么问题???
答案 0 :(得分:2)
将JSON标头添加到PHP文件的顶部:
header('Content-type: application/json');
答案 1 :(得分:1)
使用它: -
<?php
$temp = array();
foreach ( $obj as $o )
{
$temp[ $o->key] = utf8_encode($o->id);
$a[] = $temp;
}
die(json_encode(array('valid' => true,'content'=>$a)));
?>
在javascript中: -
$.ajax({
type:'POST',
url: "imoveis/carrega_bairros",
data: ({cidade:10}),
dataType:"json",
success: function(ret)
{
if(ret.valid == true)
{
// get your array as
var arr = ret.content;
alert(arr)
}
else
{
alert('error occured');
}
}
});