是否有不使用回调的$ getJSON版本? [英] Is there a version of $getJSON that doesn't use a call back?

查看:90
本文介绍了是否有不使用回调的$ getJSON版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为3rdParty javascript库实现回调,我需要返回该值,但是我需要从服务器获取该值.我需要做这样的事情:

I am implementing a callback for a 3rdParty javascript library and I need to return the value, but I need to get the value from the server. I need to do something like this:

3rdPartyObject.getCustomValue = function {
   return $.getJSON('myUrl');
}

getJson使用XMLHttpRequest(我相信它具有同步和异步行为),我可以使用同步行为吗?

getJson uses XMLHttpRequest which (I believe) has both synchronous and asynchronous behaviors, can I use the synchronouse behavior?

推荐答案

看看jQuery源代码,这是$.getJSON所做的全部事情:

Looking at the jQuery source code, this is all $.getJSON does:

getJSON: function( url, data, callback ) {
    return jQuery.get(url, data, callback, "json");
},

这是$.get的全部工作:

get: function( url, data, callback, type ) {
    // shift arguments if data argument was omitted
    if ( jQuery.isFunction( data ) ) {
        callback = data;
        data = null;
    }

    return jQuery.ajax({
        type: "GET",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
},

那里没有黑魔法.由于您需要自定义除基本$.getJSON功能以外的其他内容,因此您可以仅使用低级$.ajax函数并传递

No black magic there. Since you need to customize stuff other than the basic $.getJSON functionality, you can just use the low-level $.ajax function and pass the async option as false:

$.ajax({
    type: 'GET',
    url: 'whatever',
    dataType: 'json',
    success: function() { },
    data: {},
    async: false
});

这篇关于是否有不使用回调的$ getJSON版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆