json file and $.getJSON


json file and $.getJSON

我正试图通过使用使用$.getJSON获取json文件

$.getJSON('json/resume.json', function(data){
    alert('success');
});

但是警报信息没有来,我试过了:

$.ajax({
    type: 'POST',
    url: 'json/download.php',
}).success(function(){alert("hello")});

在这种情况下,警报以HELLO的形式出现。

我完全被卡住了。请帮助

感谢

您对两个不同的url使用两个不同请求,并将它们进行比较,就好像是相同的一样,第一个是get到json/resume.json,第二个是POST到json/download.php。第一个调用失败的唯一原因是:

json/resume.json does not exist
json/resume.json does not contain valid json

您需要设置全局ajax错误处理程序,以便从getJSON中获取错误,或者通过类似ajax的运行相同的json查询

$.ajax({
    url: 'json/resume.json',
    type: 'GET',
    dataType: 'json'
    success: function(response) {
        console.log(response)//should come into console anyway 
    },
    error: function(request, type, errorThrown) {
        message = (type=='parseerror') ? "json is invalid" : "(" + request.status + " " + request.statusText + ").";
        alert("error with request: "+message);
    }
})

我认为您应该签出发生在getJSON()中的错误,例如

$.getJSON('json/resume.json', function(data){
    alert('success');
}).error(function(e, m) { alert('error'); console.log(m); });

第一个是GET,第二个是POST-您是否在浏览器中使用了开发工具并检查了NET选项卡中的服务器500错误?

如果你的服务器方法只接受POST,那就麻烦了。

您的服务器端脚本没有返回有效的JSON,或者没有将Content-Type响应标头设置为application/json

因此,在尝试使用$.getJSON:使用脚本之前,请确保满足这两个条件

<?php
    header('Content-Type: application/json');
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
    echo json_encode($arr);
?>