代码之家  ›  专栏  ›  技术社区  ›  Pure.Krome

此jquery getjson ajax调用的回调方法有问题

  •  0
  • Pure.Krome  · 技术社区  · 13 年前

    我有一个实用程序.js文件,它通过Ajax获取一些数据。现在这个实用程序方法不知道谁会调用它。

    因此,当Ajax异步完成时,它需要将对象发送回调用者。我不知道怎么做:(

    这是我的密码…

    function someMethod(a, b, c) {
        // ... stuff ...
    
        // Now fire it off, asynchronously!
        var request = $.getJSON(url, function (jsonResult) {
            var result =
            {
                json: jsonResult,
                contentLength: request.getResponseHeader("Content-Length")
            };
    
            // TODO: Now return this result to the caller.
        });
    }
    

    当然,我不能用 return result; 因为这是异步的。我觉得我需要传递一个参数,当结果异步完成时,上面的Ajax代码需要调用这个函数。只是不知道怎么……因为记住……这是方法不知道谁在调用它。所以它不知道其他的方法和东西。

    有什么想法吗?

    1 回复  |  直到 13 年前
        1
  •  3
  •   Alex    13 年前

    function someMethod(a, b, c, callback, context) {
        // ... stuff ...
    
        // Now fire it off, asynchronously!
        var request = $.getJSON(url, function (jsonResult) {
            var result =
            {
                json: jsonResult,
                contentLength: request.getResponseHeader("Content-Length")
            };
    
            // Now return this result to the caller. With the context set
            callback.call(context, result);
    
            // Example of callback without setting the context
            //callback(result);
        });
    }