javascript – 如何从AJAX请求中返回值?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 如何从AJAX请求中返回值?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1692字,纯文字阅读大概需要3分钟。
内容图文
参见英文答案 > How do I return the response from an asynchronous call? 35个
我有一个函数,它使用var关键字声明一个变量.然后它启动一个AJAX请求来设置变量的值,然后从该函数返回该变量.
但是,我的实现失败了,我不知道为什么.
这是代码的简化版本;
function sendRequest(someargums) {
/* some code */
var the_variable;
/* some code */
request.onreadystatechange =
//here's that other function
function() {
if (request.readyState == 4) {
switch (request.status) {
case 200:
//here the variable should be changed
the_variable = request.responseXML;
/* a lot of code */
//somewhere here the function closes
}
return the_variable;
}
var data = sendRequest(someargums); //and trying to read the data I get the undefined value
解决方法:
AJAX请求是异步的.您的sendRuest函数正在被执行,正在进行AJAX请求,但它是异步发生的;所以在执行AJAX请求(以及你的onreadystatechange处理程序)之前执行sendRuest的剩余部分,因此返回时未定义the_variable.
实际上,您的代码的工作方式如下:
function sendRuest(someargums) {
/* some code */
var the_variable;
/* some code */
return the_variable;
}
var data = sendRequest(someargums);
然后一段时间后,您的AJAX请求正在完成;但现在已经太晚了
你需要使用一个叫做回调的东西:
你以前可能有过的地方
function () {
var theResult = sendRuest(args);
// do something;
}
你应该做:
function () {
sendRuest(args, function (theResult) {
// do something
});
};
并修改sendRuest,如下所示:
function sendRuest(someargums, callback) {
/* some code */
//here's that other function
request.onreadystatechange =
function() {
if (request.readyState == 4) {
switch (request.status) {
case 200:
callback(request.responseXML);
/* a lot of code */
//somewhere here the function closes
}
}
内容总结
以上是互联网集市为您收集整理的javascript – 如何从AJAX请求中返回值?全部内容,希望文章能够帮你解决javascript – 如何从AJAX请求中返回值?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。