简体   繁体   English

jQuery getJSON函数未运行

[英]jquery getJSON function not running

I'm using $.getJSON to load a JSON file. 我正在使用$ .getJSON加载JSON文件。 The file appears to load successfully (I can see its contents in Firebug below a heading that reads "GET http://siteinfo/data/library.json 304 not modified"). 该文件似乎已成功加载(我可以在Firebug中的标题为“ 未修改 GET http://siteinfo/data/library.json 304”的标题下看到其内容)。 However if I try to use console.log or alert inside the success function it doesn't work): 但是,如果我尝试使用console.log或成功功能内部的警报,则它不起作用):

$.getJSON('data/library.json', function(data){
    alert('HERE');
    console.log(data);
    $.each(data.library, function(k,v){
        console.log(k + "/" + v);

    });
});

None of the alerts or console.logs are working. 没有任何警报或console.logs在工作。 What could I be doing wrong? 我可能做错了什么?

I think it's a problem with caching, you could try doing your request like this, turning caching off 我认为这是缓存问题,您可以尝试执行这样的请求,然后关闭缓存

 $.ajax({
      dataType: "json",
      type: "get",
      url: 'data/library.json',
      cache:false,
      success: function(data){
        alert('HERE');
        console.log(data);
        $.each(data.library, function(k,v){
        console.log(k + "/" + v);
        });
      }
    });

You are getting 304 status code. 您正在获取304状态代码。 That's why response not coming in success function its going to error function because error is a function to be called if the request fails. 这就是为什么响应不会进入success函数而转到error函数的原因,因为error是请求失败时要调用的函数。

There is something wrong with server side. 服务器端出了点问题。 Read Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest? 阅读为什么使用HttpWebRequest时某些链接上出现“(304)Not Modified”错误? for more details. 更多细节。

Add this error handler in ajax request. 在ajax请求中添加此错误处理程序。 You can handle error in ajax. 您可以处理ajax中的错误。 This is following function equivalent to your getJSON 这是等效于您的getJSON以下函数

$.ajax({
    type: "get", 
    url: "data/library.json",
    datatype: "json"
    success: function (data, text) {
        alert('HERE');
        console.log(data);
        $.each(data.library, function(k,v){
            console.log(k + "/" + v);

        });
    },
   //add this error handler you'll get alert
    error: function (request, status, error) {
        alert(request.responseText);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM