我正在为3rdParty javascript库实现回调,我需要返回值,但我需要从服务器获取值.我需要做这样的事情:
3rdPartyObject.getCustomValue = function {
return $.getJSON('myUrl');
}
Run Code Online (Sandbox Code Playgroud)
getJson使用XMLHttpRequest(我相信)同时具有同步和异步行为,我可以使用同步行为吗?
Pao*_*ino 103
看一下jQuery源代码,这就是全部$.getJSON:
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
Run Code Online (Sandbox Code Playgroud)
这一切都是$.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
});
},
Run Code Online (Sandbox Code Playgroud)
那里没有黑魔法.由于您需要自定义除基本$.getJSON功能之外的其他内容,因此您可以使用低级$.ajax功能并将async选项作为false 传递:
$.ajax({
type: 'GET',
url: 'whatever',
dataType: 'json',
success: function() { },
data: {},
async: false
});
Run Code Online (Sandbox Code Playgroud)
小智 15
您还可以在拨打电话之前使用以下内容:
$.ajaxSetup( { "async": false } );
Run Code Online (Sandbox Code Playgroud)
我不知道"async"属性的范围,我怀疑它是一个全局配置.因此,请考虑在同步调用后是否要将其更改回true.
例:
3rdPartyObject.getCustomValue = function {
$.ajaxSetup( { "async": false } );
var result = $.getJSON('myUrl');
$.ajaxSetup( { "async": true } );
return result;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
var jsonObjectInstance = $.parseJSON(
$.ajax(
{
url: "json_data_plz.cgi",
async: false,
dataType: 'json'
}
).responseText
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43118 次 |
| 最近记录: |