jQuery 是否有不使用回调的 $getJSON 版本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/933713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a version of $getJSON that doesn't use a call back?
提问by tpower
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:
我正在为 3rdParty javascript 库实现回调,我需要返回该值,但我需要从服务器获取该值。我需要做这样的事情:
3rdPartyObject.getCustomValue = function {
return $.getJSON('myUrl');
}
getJson uses XMLHttpRequest which (I believe) has both synchronous and asynchronous behaviors, can I use the synchronouse behavior?
getJson 使用 XMLHttpRequest(我相信)具有同步和异步行为,我可以使用同步行为吗?
回答by Paolo Bergantino
Looking at the jQuery source code, this is all $.getJSON
does:
查看 jQuery 源代码,这就是全部$.getJSON
:
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
And this is all $.get
does:
这就是全部$.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
});
},
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 optionas false:
那里没有黑魔法。由于您需要自定义基本$.getJSON
功能以外的内容,您可以只使用低级$.ajax
函数并将async 选项传递为 false:
$.ajax({
type: 'GET',
url: 'whatever',
dataType: 'json',
success: function() { },
data: {},
async: false
});
回答by Jonathan
You can also use the following before making your call:
您还可以在拨打电话之前使用以下内容:
$.ajaxSetup( { "async": false } );
I do not know the scope of the "async" property, I suspect that it is a global config. So consider whether you want to change this back to true after your synchronous call.
我不知道“async”属性的范围,我怀疑它是一个全局配置。因此,请考虑是否要在同步调用后将其改回 true。
example:
例子:
3rdPartyObject.getCustomValue = function {
$.ajaxSetup( { "async": false } );
var result = $.getJSON('myUrl');
$.ajaxSetup( { "async": true } );
return result;
}
回答by ph1g
var jsonObjectInstance = $.parseJSON(
$.ajax(
{
url: "json_data_plz.cgi",
async: false,
dataType: 'json'
}
).responseText
);
回答by ph1g
But unless i am mistaken this code wouldn't work:
但除非我弄错了,否则这段代码将不起作用:
3rdPartyObject.getCustomValue = function {
var json = $.ajax({
type: 'GET',
url: 'whatever',
dataType: 'json',
success: function() { },
data: {},
async: false
});
return json;
}
As $.ajax returns the XHR object not the parsed json object.
因为 $.ajax 返回 XHR 对象而不是解析的 json 对象。
You would need to do something more like:
您需要做更多类似的事情:
var jsonLoader = function(url){
this.url = url;
this.rawData = {};
this.getRawData();
};
jsonLoader.prototype.getRawData = function(){
var json = $.ajax({
type: 'GET',
url: this.url,
dataType: 'json',
success: this.getRawData(this),
data: {},
async: false
});
};
jsonLoader.prototype. getRawData = function(self){
return function(json){self.rawData = json;};
};
var loadMe = new jsonLoader("Data.json");
loadMe.rawData //has the parsed json object
In fact there is probably a much neater way of achieving the same
事实上,可能有一种更简洁的方法来实现相同的目标
回答by Steve Sheldon
If anybody ever has to do this in rails, I have a pretty clean way like this:
如果有人不得不在 Rails 中执行此操作,我有一个非常干净的方法:
Setup your controller like this:
像这样设置你的控制器:
def my_ajax_action respond_to do |format| # if you use render, you won't need a view page, the ":json =>" part takes care of all # the formatting format.json { render :json => @variable_containing_json } end end
def my_ajax_action respond_to do |format| # if you use render, you won't need a view page, the ":json =>" part takes care of all # the formatting format.json { render :json => @variable_containing_json } end end
Setup the call in Javascript
在 Javascript 中设置调用
function doAjaxWork( ) { var ret; $.ajax({ type: 'GET', url: '/controller/action/param', dataType: 'json', complete: function(response) { ret = eval('(' + response.responseText + ')'); }, async: false }); return ret; }
function doAjaxWork( ) { var ret; $.ajax({ type: 'GET', url: '/controller/action/param', dataType: 'json', complete: function(response) { ret = eval('(' + response.responseText + ')'); }, async: false }); return ret; }
Of course, don't do this sync stuff unless you have to. Oh and while I am showing javascript with urls in it, check out JSRoutes... it's makes these really clean.
当然,除非必须,否则不要执行此同步操作。哦,当我展示带有 url 的 javascript 时,请查看JSRoutes......它使这些非常干净。
回答by slider
The scope of the async property is global, your method will synchronize the call.
async 属性的范围是全局的,您的方法将同步调用。