2013-02-05 34 views
3

我目前在本地主机上运行:JQuery.getJSON不报警JSON

$.getJSON("http://localhost/call", function(json) { 
    alert(json.something); 
}); 

http://localhost/call回报{something:1},但没有被提醒。

+1

你JSON的反应似乎是无效的。而从jQuery 1.4开始,如果JSON文件包含语法错误,请求通常会自动失败 - http://api.jquery.com/jQuery.getJSON/ – Tom

+1

您应该使用服务器端语言提供的方法将数据结构转换为JSON,而不是单独构建它。 *编辑:* http://php.net/manual/en/function.json-encode.php –

回答

8
{something:1} 

心不是一个有效JSON字符串,但

{"something":1} 

是。

如果更换

$.ajax({ 
    url: 'http://localhost/call', 
    dataType: 'json', 
    success: function(){}, 
    error: function(xhr, textStatus, errorThrown){ 
     //you should get a parse error and end up here 
    } 
}); 

你的电话,你应该在error回调结束。

在你的PHP文件:

header('Cache-Control: no-cache, must-revalidate'); 
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); 
header('Content-type: application/json'); 

$arr = array('something' => 1, 'somethingelse' => 2); 

echo json_encode($arr); 
+0

Doggonit,我知道它会是这样的。 – Babiker

+0

@Babiker嘿嘿,我们都犯错误;)你使用什么服务器端语言? – Johan

+0

告诉我一下,PHP。 – Babiker