javascript - $.getJSON为什么不执行其中的函数

 静心-苑 发布于 2022-11-16 15:34
$("#sign-in-btn").click(function () {
    $.getJSON("fakedata.js?1.2.1", function(json){
        alert("123");
    });
    return false; // 因为在form表单中,所以return false
});

这是js文件中的json数据

var data = {
  "user": [
    {
      "id": "1",
      "username": "Bill",
      "password": "password"
    },
    {
      "id": "2",
      "username": "George",
      "password": "password"
    },
    {
      "id": "3",
      "username": "Thomas",
      "password": "password"
    }
  ]
}

firebug中能看到可以读取到文件,但是就是不执行function(json){alert("123");}的内容。

3 个回答
  • 这个问题似乎是JQuery的BUG,具体原因我也在研究中,希望题主能提供一些线索。
    下面的代码来自JQuery v1.11.1
    https://github.com/jquery/jquery/blob/1....

    • 定位到771行的getJSON入口

    getJSON: function( url, data, callback ) {
        return jQuery.get( 'fakedata.js', function(json) {
            alert('123');
        }, undefined, 'json');
    },
    // 调用楼主的方法后执行jQuery.get( url, data, callback, "json" );
    • 定位到780行

    jQuery.each( [ "get", "post" ], function( i, method ) {
        jQuery[ method ] = function( url, data, callback, type ) {
            // shift arguments if data argument was omitted
            if ( jQuery.isFunction( data ) ) {
                type = type || callback;
                callback = data;
                data = undefined;
            }
    
            return jQuery.ajax({
                url: url,
                type: method,
                dataType: type,
                data: data,
                success: callback
            });
        };
    });
    // 最终执行
    jQuery.ajax({
        url: 'fakedata.js',
        type: 'get',
        dataType: 'json',    //MIME: "application/json, text/javascript"
        data: undefined,
        success: function(json) {
            alert('123');
        }
    });

    事实上这个请求一切正常,你可以先尝试切换到原生的XMLHTTPRquest对象能否正常获取先。

    补充:题主获取的js文件不是规范的json,建议修改一下数据原型。

    2022-11-16 15:56 回答
  • "var data =" 删除再试

    2022-11-16 15:56 回答
  • {
      "user": [
        {
          "id": "1",
          "username": "Bill",
          "password": "password"
        },
        {
          "id": "2",
          "username": "George",
          "password": "password"
        },
        {
          "id": "3",
          "username": "Thomas",
          "password": "password"
        }
      ]
    }

    js文件中只保留一个json字符串,不能是表达式,因为读取到的内容不是json, 所以回调函数不执行

    2022-11-16 15:56 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有