问题描述
我正在为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版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!