0

我正在发送一个 url 以获取 json 响应,但我将响应作为对象而不是“正确的响应”(json 数据)..这里有什么问题..

var JsonHandler = function(){
    return{
        json : function(url){
            return $.getJSON(url, function(data){
                return data;
            });
        }
    }
};

(function ($) {

    var path = "js/data.json";
    var getJson = new JsonHandler();
    console.log(getJson.json(path));// i am getting a object instead of json response..

})(jQuery);
4

4 回答 4

1

您需要在回调中处理您的逻辑。你应该怎么做取决于你的代码。

如果你把console.dir(data)而不是return data;你应该看到你的回应。

所以你应该把应该对数据做一些事情的相应代码放在那里。或者我们jQuery.proxy或者Function.prototype.bind将你的回调绑定到一个对象。但无论您如何创建传递给 的回调getJson,它都必须是您使用数据的执行路径的来源。

为了说明异步行为,请检查您的代码的此修改:

var JsonHandler = function(){
    return{
        json : function(url){
            return $.getJSON(url, function(data){
                console.log("data received");
                console.dir(data);
            });
        }
    }
};

(function ($) {

    var path = "js/data.json";
    var getJson = new JsonHandler();
    console.log("before json request");
    getJson.json(path);// i am getting a object instead of json response..
    console.log("after json request");

})(jQuery);

编辑

这是一个发布/订阅系统的示例(代码目前更多是伪代码 - 尚未对其进行语法错误测试,但我会在几个小时内修复可能存在的错误)

var JsonHandler = {
    request : function( url, params, key ) {
        $.getJSON(url, params, function(data){
            //because of js scopes the 'key'  is the one that is used for requesting the data
            JsonHandler._publishData(data, key);
        });
    },

    _subcribers : {},

    /* 
        key could also be path like this: 
                      /news/topic1
                      /news/topic2
                      /news

        so code  subscribes for '/new'  it will be notifed for  /news/topic1, /news/topic2,  /news
    */
    subscribe : function( key, callback ) {

        /*
        The path logic is missing here but should not be that problematic to added if you understood the idea 

        */

        this._subcribers[key] = this._subcribers[key]||[];
        this._subcribers[key].push(callback);

    },


    _publishData : function( data, key ) {
        /*
        check if there are subscribers for that key and if yes call notify them
                    This part is also missing the path logic mention above, is just checks for the key
        */
        if ( this._subcribers[key] ) {
            var subscribers = this._subcribers[key];

            for( var i = 0, count = subscribers.length ; i<count ; i++ ) {
                subscribers[i](data,key);
            }
        }

    }


}

var AnObject = function() {
}

AnObject.prototype = {
    updateNews : function(data, key) {
        console.log("received data for key: "+ key);
        console.dir(data);
    }
};


var obj = new AnObject();

//add a simple callback
JsonHandler.subscribe( "/news", function(data, key ) ) {
    console.log("received data for key: "+ key);
    console.dir(data);
});

//add a callback to a 'method' of an object
JsonHandler.subscribe( "/news", obj.updateNews.bind(obj) );


JsonHandler.request("some/url",{/* the parameters */}, "/news");
于 2013-06-17T09:34:28.570 回答
1

$.getJSON不返回 JSON。它是异步的。调用return回调不会改变这一点。

相反,使用这个:

var JsonHandler = function(callback){
    return {
        json : function(url){
            return $.getJSON(url, callback);
        }
    }
};

(function ($) {

    var path = "js/data.json";
    var getJson = new JsonHandler(function(data){console.log(data)});
    getJson.json(path);
})(jQuery);
于 2013-06-17T09:32:12.170 回答
0
 $.ajax({
              type: "POST",
              url: "frmTrialBalance.aspx/GetTheTrialBalanceOriginalCurrPriorTwoQuarter",
              data: "{ CompanyId:'" + s + "',EndDate:'" + datet + "'}",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function (msg) {


                 ***var data = $.parseJSON(msg.d);***

                  LoopGetTrialBalanceORIGINALPriorYearMonthQuarter(data);
                  IncreaseIframeHeight();
              },
              error: AjaxFailed
          });*emphasized text*
于 2013-06-17T10:02:48.540 回答
0

您必须在回调函数中完成所有代码,然后您将获得数据对象。$.getJSON 返回 XMLHTTPRequest 对象。

    var JsonHandler = function () {
        return {
            json: function (url) {
                $.getJSON(url, {}, function (data) {
                    console.log(data);
                });
            }
        }
    };

    (function ($) {
        var path = "js/data.json";
        var getJson = new JsonHandler();
        getJson.json(path); // i am getting a object instead of json response..
    })(jQuery);
于 2013-06-17T12:11:52.657 回答