【问题标题】:Json file wont load in with jquery .getJSON()Json 文件不会使用 jquery .getJSON() 加载
【发布时间】:2016-11-03 19:22:30
【问题描述】:

我正在尝试使用 jquery 的 getJSON() 将外部 json 文件分配给 var。在我的 JSON 文件中,我的代码与 outp 完全相同。当我尝试 console.log 数据变量中的内容时,它只显示 readyState1。这意味着我已与服务器连接,但为什么请求不继续?这是我的代码:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
    var url = "content.json"
    var outp = {
                    low         :   0,
                    high        :   99,
                    name        :   "Fritz",
                    rufnummer   :   "012",
                    faxnummer   :   "345",
                    mobil       :   "678",
                    mail        :   "mail@mail.mail",  
                }

    $('#find').on("click", function(){

        var data = $.getJSON(url);

        console.log(data);
        console.log(outp);
        console.log("Hi");

    });
});
</script>
</head>
<body>
    <p>Postleitszahl:</p>
    <input type="number" autocomplete="on" name="inp" id="inp">
    <button type="button" id="find">Finden</button>
    <p class="output"></p>
</body>
</html>

【问题讨论】:

    标签: jquery json getjson readystate


    【解决方案1】:

    $.getJSON 方法执行异步调用,这意味着您不会将接收到的数据作为返回值。 为了访问服务器发送的响应,您需要注册一个回调:

    $.getJSON(url, function(data) {
          console.log(data);
          //do what you need to do with your data here
    });
    

    参考http://api.jquery.com/jquery.getjson/

    希望对你有帮助

    【讨论】:

    • 感谢您的帮助,我进行了更改,但现在我的 console.log 没有显示任何内容! varr 数据现在应该从 json 中保存我的对象,对吧?
    • 正确。仅在请求成功的情况下才调用定义的函数。在“getJSON”“请求成功”的情况下,答案是有效的 json,响应还应包括标题“Content-Type:application/json”。进一步调试请看参考链接,尤其是“The jqXHR Object”一节
    【解决方案2】:

    $.getJSON 异步运行。在您当前的代码中,您试图在请求完成之前访问数据。

    您需要使用成功回调来访问响应。

    $.getJSON(url, function(data) {
        console.log(data);
        console.log(outp);
        console.log("Hi");
    });
    

    【讨论】:

      猜你喜欢
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      相关资源
      最近更新 更多