0

On a page called test.html I want to retrieve some JSON data from a page called test2.php by jquery ajax.

the following code does not work

test.html:

$.ajax({ 
    url:"test2.php",
    type:"POST",
    dataType: "json",
    success: function(data){
        alert(data.b.d);
    }
});

test2.php:

<?php
    $c= '{"a":{"d":6994,"e":20003,"f":7968,"g":12505,"h":6814},"b":{"d":10623,"e":3404,"f":405,"g":17066,"h":24219}}';
    echo $c;
?>
4

3 回答 3

0

我建议使用像Firebug这样的 JS 调试工具 检查您的请求是否返回有效响应。

于 2012-11-19T15:35:26.990 回答
0

Your test2.php does not contain the proper headers. Add this just after

header('Content-type: application/json');

于 2012-11-19T15:21:39.110 回答
0

如果您没有随请求发送任何数据,则可能不需要使用 POST。您可以改为 GET 。甚至还有一个有用的速记方法:

$.get("test2.php", function(data) {
    // handle your data here
}, 'json'); 

test2.php你做事情的艰难方式。无需尝试构建 JSON 字符串,只需构建要发送给客户端的数据结构即可。然后用json_encode(). 您应该发送 JSON 内容类型标头,以便 jQuery 知道如何解码数据:

$c = array(
    'a'=>array(
        'd' =>6994,
        'e' => 2003,
        'f' => 7968,
     )
    // and so on...
);
header('content-type: application/json');
echo json_encode($c);
于 2012-11-19T15:52:47.583 回答