[英]Syntactic sugar to Prototype's Ajax function
I would like to create syntactic sugar to Ajax.Response()
. 我想为
Ajax.Response()
创建语法糖。
Like this: 像这样:
AjaxGet = function(url) {
ar = new Ajax.Request(url,
{ onSuccess: function(transport) {
alert(transport.responseText);
return transport.responseText;
}
});
return ar.responseText;
}
So that 以便
title = AjaxGet('/favouriteMovie?horrors=true')
would store to title
variable result of Ajax request. 将存储到Ajax请求的
title
变量结果。 But the function code above is not working, not returning responseText
但上面的功能代码不起作用,不返回
responseText
It is issue with the ajax call being asynchronous. 这是ajax调用是异步的问题。 easier fix would be to specify asynchronous: false in your Ajax.Get call.
更简单的修复方法是在Ajax.Get调用中指定asynchronous:false。 Eg:
例如:
AjaxGet = function(url) {
ar = new Ajax.Request(url,
{ onSuccess: function(transport) {
alert(transport.responseText);
return transport.responseText;
},
asynchronous: false
});
return ar.responseText;
}
However I suggest to retain the async functionality of the requests and then tweak th on Success function callbacks as needed. 但是,我建议保留请求的异步功能,然后根据需要调整Success函数的回调。
You can only do this if you use synchronous Ajax, which you should never ever do . 仅当使用同步Ajax时才可以执行此操作,而永远不要这样做 。 The user interface of the whole browser will become unresponsive for the duration of the request, which you have no way to predict.
整个浏览器的用户界面在请求期间将无响应,您无法预测。
So the best you can do will involve a callback of some sort: 所以你能做的最好的事情将涉及某种回调:
function AjaxGet(url, callback) {
new Ajax.Request(url, {
onSuccess: function(xhr){ callback(xhr.responseText) }
});
}
There are problems with this approach, though: 但是,这种方法存在一些问题:
For these reasons I recommend you go with the full Ajax.Request
whenever you need it. 由于这些原因,我建议您在需要时使用完整的
Ajax.Request
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.