Php ajax json解码返回未定义的not数据
我试图通过ajax从PHP脚本中提取json数据,但它不起作用Php ajax json解码返回未定义的not数据,php,ajax,json,Php,Ajax,Json,我试图通过ajax从PHP脚本中提取json数据,但它不起作用 while ($row = mysql_fetch_array($result)) { $response = array( 'hello' => $row['name'] ); $responses[] = $response; } echo json_encode($responses); 然后我使用这个JavaScript $('.clickme').click(function
while ($row = mysql_fetch_array($result)) {
$response = array(
'hello' => $row['name']
);
$responses[] = $response;
}
echo json_encode($responses);
然后我使用这个JavaScript
$('.clickme').click(function() {
$.ajax({
url: 'http://example.com/testFixGet.php?department=1',
dataType: 'json',
data: 'manufacturer=alpine,kicker',
success: function(json) {
alert(json['hello']);
$('.result_new').html(json);
}
});
});
对话框显示:“未定义”
但是,如果我真的加载了php页面,数据是json解码的,它看起来是这样的:
[{"hello":"Rand McNally Soft Case for Most 5\" GPS"}]
您正在设置内容类型吗
header('Content-type: application/json');
顺便说一下
[{"hello":"Rand McNally Soft Case for Most 5\" GPS"}]
它是一个数组
alert(json[0]["hello"]);
循环
var bar = [{"a":"1"},{"a":"2"},{"a":"3"}]
$.each( bar, function(i, jObj){
alert( jObj.a );
});
您会注意到JSON负载包含一个带有一个object元素的数组。试一试
alert(json[0]['hello']);
而且,getJSON()
更加简洁
$('.clickme').click(function() {
$.getJSON('http://example.com/testFixGet.php', {
department: 1,
manufacturer: 'alpine,kicker'
}, function(json) {
// loop over results
for (var i = 0; i < json.length; i++) {
var response = json[i];
console.log(response);
}
});
});
$('.clickme')。单击(函数(){
$.getJSON('http://example.com/testFixGet.php', {
部门:1,,
制造商:“阿尔卑斯,踢球者”
},函数(json){
//循环结果
for(var i=0;i
试试这个:
$('.clickme').click(function() {
$.getJSON('testFixGet.php', { manufacturer: "alpine,kicker", department: "1" }, function(json) {
alert(json[0].hello);
$('.result_new').html(json);
} );
}
这是可行的,但我想返回每一行,那么我会在我的成功函数中执行foreach语句吗?我已经完全复制了它,但它没有做任何事情,也没有显示在我的firebug中。除此之外,我只添加了一个“.clickme”@RPM Oops,错过了那个。过于关注其他位,但在执行此操作时,它仍然只返回1个结果:$('.result_new').html(response.hello);我将头设置为json,但是我会在success函数中执行foreach语句以返回所有hello吗?