jQuery:ajax调用成功后返回数据
本文翻译自:jQuery: Return data after ajax call success [duplicate]
I have something like this, where it is a simple call to a script that gives me back a value, a string.. 我有类似这样的内容,它是对脚本的简单调用,该脚本给了我一个值,一个字符串。
function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {
return data;
}
});
}
but if I call something like this 但是如果我这样称呼
var output = testAjax(svar); // output will be undefined...
so how can I return the value? 那么我该如何返回值? the below code does not seem to work either... 下面的代码似乎也不起作用...
function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {
}
});
return data;
}
#1楼
参考:https://stackoom.com/question/MJ7B/jQuery-ajax调用成功后返回数据
#2楼
Idk if you guys solved it but I recommend another way to do it, and it works :) Idk,如果你们解决了,但我建议您采用另一种方法来解决,它是可行的:)
ServiceUtil = ig.Class.extend({
base_url : 'someurl',
sendRequest: function(request)
{
var url = this.base_url + request;
var requestVar = new XMLHttpRequest();
dataGet = false;
$.ajax({
url: url,
async: false,
type: "get",
success: function(data){
ServiceUtil.objDataReturned = data;
}
});
return ServiceUtil.objDataReturned;
}
})
So the main idea here is that, by adding async: false, then you make everything waits until the data is retrieved. 因此,这里的主要思想是,通过添加async:false,然后让所有内容等待,直到检索到数据为止。 Then you assign it to a static variable of the class, and everything magically works :) 然后将其分配给该类的静态变量,然后一切都会神奇地起作用:
#3楼
See jquery docs example: http://api.jquery.com/jQuery.ajax/ (about 2/3 the page) 请参阅jquery文档示例: http : //api.jquery.com/jQuery.ajax/ (约2/3的页面)
You may be looking for following code: 您可能正在寻找以下代码:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Same page...lower down. 同一页...降低。
#4楼
The only way to return the data from the function would be to make a synchronous call instead of an asynchronous call, but that would freeze up the browser while it's waiting for the response. 从函数返回数据的唯一方法是进行同步调用而不是异步调用,但这将使浏览器在等待响应时冻结。
You can pass in a callback function that handles the result: 您可以传入一个处理结果的回调函数:
function testAjax(handleData) {
$.ajax({
url:"getvalue.php",
success:function(data) {
handleData(data);
}
});
}
Call it like this: 这样称呼它:
testAjax(function(output){
// here you use the output
});
// Note: the call won't wait for the result,
// so it will continue with the code here while waiting.
#5楼
Note: This answer was written in February 2010. 注意:此答案写于2010年2月。
See updates from 2015, 2016 and 2017 at the bottom. 请参阅底部的2015、2016和2017年更新。
You can't return anything from a function that is asynchronous. 您不能从异步函数返回任何内容。 What you can return is a promise . 您可以返回的是一个承诺 。 I explained how promises work in jQuery in my answers to those questions: 我在回答以下问题时解释了Promise如何在jQuery中工作:
- JavaScript function that returns AJAX call data 返回AJAX调用数据的JavaScript函数
- jQuery jqXHR - cancel chained calls, trigger error chain jQuery jqXHR-取消链式调用,触发错误链
If you could explain why do you want to return the data and what do you want to do with it later, then I might be able to give you a more specific answer how to do it. 如果您可以解释为什么要返回数据以及以后要使用什么数据,那么我也许可以为您提供具体的答案。
Generally, instead of: 通常,代替:
function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {
return data;
}
});
}
you can write your testAjax function like this: 您可以这样编写testAjax函数:
function testAjax() {
return $.ajax({
url: "getvalue.php"
});
}
Then you can get your promise like this: 然后,您可以像这样实现您的承诺:
var promise = testAjax();
You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: 您可以存储您的诺言,可以将其传递,可以将其用作函数调用中的参数,也可以从函数中返回它,但是当您最终想要使用 AJAX调用返回的数据时,您必须像这样做:
promise.success(function (data) {
alert(data);
});
(See updates below for simplified syntax.) (有关简化语法,请参见下面的更新。)
If your data is available at this point then this function will be invoked immediately. 如果此时您的数据可用,则将立即调用此函数。 If it isn't then it will be invoked as soon as the data is available. 如果不是,那么它将在数据可用时立即调用。
The whole point of doing all of this is that your data is not available immediately after the call to $.ajax because it is asynchronous. 这样做的全部目的是,在调用$ .ajax之后,您的数据不立即可用,因为它是异步的。 Promises is a nice abstraction for functions to say: I can't return you the data because I don't have it yet and I don't want to block and make you wait so here's a promise instead and you'll be able to use it later, or to just give it to someone else and be done with it. Promises是一个很好的函数抽象:我无法返回数据,因为我还没有数据,并且我不想阻塞并让您等待,所以这是一个诺言 ,您将能够以后使用它,或仅将其提供给其他人并完成它。
UPDATE (2015) 更新(2015)
Currently (as of March, 2015) jQuery Promises are not compatible with the Promises/A+ specification which means that they may not cooperate very well with other Promises/A+ conformant implementations . 当前(截至2015年3月),jQuery Promises与Promises / A +规范不兼容,这意味着它们可能无法与其他与Promises / A +兼容的实现很好地协作。
However jQuery Promises in the upcoming version 3.x will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out). 但是,即将发布的3.x版本中的jQuery Promises 将与Promises / A +规范兼容(感谢Benjamin Gruenbaum指出了这一点)。 Currently (as of May, 2015) the stable versions of jQuery are 1.x and 2.x. 当前(截至2015年5月),jQuery的稳定版本为1.x和2.x。
What I explained above (in March, 2011) is a way to use jQuery Deferred Objects to do something asynchronously that in synchronous code would be achieved by returning a value. 我上面(2011年3月)所解释的是一种使用jQuery Deferred Objects异步执行某项操作的方法,该方法在同步代码中将通过返回一个值来实现。
But a synchronous function call can do two things - it can either return a value (if it can) or throw an exception (if it can't return a value). 但是同步函数调用可以做两件事-它可以返回值(如果可以)或引发异常(如果它不能返回值)。 Promises/A+ addresses both of those use cases in a way that is pretty much as powerful as exception handling in synchronous code. Promises / A +以与同步代码中异常处理一样强大的方式解决了这两种用例。 The jQuery version handles the equivalent of returning a value just fine but the equivalent of complex exception handling is somewhat problematic. jQuery版本可以处理返回值的问题,但是复杂异常处理的问题有些麻烦。
In particular, the whole point of exception handling in synchronous code is not just giving up with a nice message, but trying to fix the problem and continue the execution, or possibly rethrowing the same or a different exception for some other parts of the program to handle. 特别是,同步代码中异常处理的全部要点不仅仅是放弃一个好消息,而是试图解决问题并继续执行,或者可能将相同或不同的异常抛出给程序的其他部分以处理。 In synchronous code you have a call stack. 在同步代码中,您有一个调用堆栈。 In asynchronous call you don't and advanced exception handling inside of your promises as required by the Promises/A+ specification can really help you write code that will handle errors and exceptions in a meaningful way even for complex use cases. 在异步调用中,您不会这样做,并且Promises / A +规范要求的Promise中的高级异常处理确实可以帮助您编写代码,即使对于复杂的用例,也可以以有意义的方式处理错误和异常。
For differences between jQuery and other implementations, and how to convert jQuery promises to Promises/A+ compliant, see Coming from jQuery by Kris Kowal et al. 有关jQuery与其他实现之间的差异以及如何将jQuery Promise转换为Promises / A +兼容的方法,请参阅Kris Kowal等人的《来自jQuery的书》。 on the Q library wiki and Promises arrive in JavaScript by Jake Archibald on HTML5 Rocks. 在Q库Wiki上, Promises由Jake Archibald在HTML5 Rocks上使用JavaScript到达 。
How to return a real promise 如何兑现真实的承诺
The function from my example above: 我上面的示例中的函数:
function testAjax() {
return $.ajax({
url: "getvalue.php"
});
}
returns a jqXHR object, which is a jQuery Deferred Object . 返回jqXHR对象,它是jQuery Deferred Object 。
To make it return a real promise, you can change it to - using the method from the Q wiki : 为了使它返回真实的承诺,您可以使用Q wiki中的方法将其更改为-:
function testAjax() {
return Q($.ajax({
url: "getvalue.php"
}));
}
or, using the method from the HTML5 Rocks article : 或者,使用HTML5 Rocks文章中的方法 :
function testAjax() {
return Promise.resolve($.ajax({
url: "getvalue.php"
}));
}
This Promise.resolve($.ajax(...))
is also what is explained in the promise
module documentation and it should work with ES6 Promise.resolve()
. 这Promise.resolve($.ajax(...))
也是什么的说明中promise
模块文档 ,它应该与工作ES6 Promise.resolve()
To use the ES6 Promises today you can use es6-promise module's polyfill()
by Jake Archibald. 要今天使用ES6 Promises,可以使用Jake Archibald 编写的es6-promise模块的polyfill polyfill()
。
To see where you can use the ES6 Promises without the polyfill, see: Can I use: Promises . 要查看没有polyfill的ES6 Promises可以在哪里使用,请参阅: 我可以使用:Promises 。
For more info see: 有关更多信息,请参见:
- http://bugs.jquery.com/ticket/14510 http://bugs.jquery.com/ticket/14510
- https://github.com/jquery/jquery/issues/1722 https://github.com/jquery/jquery/issues/1722
- https://gist.github.com/domenic/3889970 https://gist.github.com/domenic/3889970
- http://promises-aplus.github.io/promises-spec/ http://promises-aplus.github.io/promises-spec/
- http://www.html5rocks.com/en/tutorials/es6/promises/ http://www.html5rocks.com/zh-CN/tutorials/es6/promises/
Future of jQuery jQuery的未来
Future versions of jQuery (starting from 3.x - current stable versions as of May 2015 are 1.x and 2.x) will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out in the comments). jQuery的未来版本(从3.x开始-截至2015年5月的当前稳定版本为1.x和2.x)将与Promises / A +规范兼容(感谢Benjamin Gruenbaum在评论中指出了这一点)。 "Two changes that we've already decided upon are Promise/A+ compatibility for our Deferred implementation [...]" ( jQuery 3.0 and the future of Web development ). “我们已经确定的两个更改是对我们的Deferred实现的Promise / A +兼容性[...] ( jQuery 3.0和Web开发的未来 )。 For more info see: jQuery 3.0: The Next Generations by Dave Methvin and jQuery 3.0: More interoperability, less Internet Explorer by Paul Krill. 有关更多信息,请参见:Dave Methvin撰写的jQuery 3.0:The Next Generations和Paul Krill撰写的jQuery 3.0:更多的互操作性,以及更少的Internet Explorer 。
Interesting talks 有趣的演讲
- Boom, Promises/A+ Was Born by Domenic Denicola (JSConfUS 2013) Boom,Promises / A +出自Domenic Denicola(JSConfUS 2013)
- Redemption from Callback Hell by Michael Jackson and Domenic Denicola (HTML5DevConf 2013) 迈克尔·杰克逊(Michael Jackson)和多米尼克·丹尼科拉(Domenic Denicola) 从回调地狱中救赎 (HTML5DevConf 2013)
- JavaScript Promises by David M. Lee (Nodevember 2014) David M.Lee的JavaScript Promises (2014年11月)
UPDATE (2016) 更新(2016)
There is a new syntax in ECMA-262, 6th Edition, Section 14.2 called arrow functions that may be used to further simplify the examples above. ECMA-262,第6版,第14.2节中有一种新的语法,称为箭头函数 ,可用于进一步简化上面的示例。
Using the jQuery API, instead of: 使用jQuery API,而不是:
promise.success(function (data) {
alert(data);
});
you can write: 你可以写:
promise.success(data => alert(data));
or using the Promises/A+ API: 或使用Promises / A + API:
promise.then(data => alert(data));
Remember to always use rejection handlers either with: 请记住,始终将拒绝处理程序与以下项一起使用:
promise.then(data => alert(data), error => alert(error));
or with: 或搭配:
promise.then(data => alert(data)).catch(error => alert(error));
See this answer to see why you should always use rejection handlers with promises: 请参阅以下答案,以了解为什么应始终对诺言使用拒绝处理程序:
Of course in this example you could use just promise.then(alert)
because you're just calling alert
with the same arguments as your callback, but the arrow syntax is more general and lets you write things like: 当然,在此示例中,您可以仅使用promise.then(alert)
因为您只是使用与回调相同的参数来调用alert
,但是arrow语法更通用,可以让您编写如下内容:
promise.then(data => alert("x is " + data.x));
Not every browser supports this syntax yet, but there are certain cases when you're sure what browser your code will run on - eg when writing a Chrome extension , a Firefox Add-on , or a desktop application using Electron, NW.js or AppJS (see this answer for details). 并非每种浏览器都支持此语法,但是在某些情况下,您可以确定您的代码将在哪种浏览器上运行-例如,在编写Chrome扩展程序 , Firefox附加组件或使用Electron,NW.js或桌面应用程序时AppJS(有关详细信息,请参见此答案 )。
For the support of arrow functions, see: 有关箭头功能的支持,请参见:
- http://caniuse.com/#feat=arrow-functions http://caniuse.com/#feat=arrow-functions
- http://kangax.github.io/compat-table/es6/#test-arrow_functions http://kangax.github.io/compat-table/es6/#test-arrow_functions
UPDATE (2017) 更新(2017)
There is an even newer syntax right now called async functions with a new await
keyword that instead of this code: 现在有一种甚至更新的语法,称为异步函数,带有一个新的await
关键字,而不是以下代码:
functionReturningPromise()
.then(data => console.log('Data:', data))
.catch(error => console.log('Error:', error));
lets you write: 让您编写:
try {
let data = await functionReturningPromise();
console.log('Data:', data);
} catch (error) {
console.log('Error:', error);
}
You can only use it inside of a function created with the async
keyword. 您只能在使用async
关键字创建的函数中使用它。 For more info, see: 有关更多信息,请参见:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/await
For support in browsers, see: 有关浏览器的支持,请参阅:
For support in Node, see: 有关Node的支持,请参见:
- http://node.green/#ES2017-features-async-functions http://node.green/#ES2017-features-async-functions
In places where you don't have native support for async
and await
you can use Babel: 在您没有本地支持async
并await
,可以使用Babel:
- https://babeljs.io/docs/plugins/transform-async-to-generator/ https://babeljs.io/docs/plugins/transform-async-to-generator/
or with a slightly different syntax a generator based approach like in co
or Bluebird coroutines: 或使用稍有不同的语法,使用基于生成器的方法(例如co
或Bluebird协程):
- https://www.npmjs.com/package/co https://www.npmjs.com/package/co
- http://bluebirdjs.com/docs/api/promise.coroutine.html http://bluebirdjs.com/docs/api/promise.coroutine.html
More info 更多信息
Some other questions about promises for more details: 有关承诺的其他一些问题,以获取更多详细信息:
- promise call separate from promise-resolution 承诺电话与承诺解决方案分开
- Q Promise delay Q承诺延迟
- Return Promise result instead of Promise 返回Promise结果而不是Promise
- Exporting module from promise result 从承诺结果中导出模块
- What is wrong with promise resolving? 诺言解决有什么问题?
- Return value in function from a promise block 从promise块返回函数中的值
- How can i return status inside the promise? 我如何在承诺中退还身份?
- Should I refrain from handling Promise rejection asynchronously? 我应该避免异步处理Promise拒绝吗?
- Is the deferred/promise concept in JavaScript a new one or is it a traditional part of functional programming? JavaScript中的延迟/承诺概念是一个新概念还是功能编程的传统组成部分?
- How can I chain these functions together with promises? 如何将这些功能与承诺链接在一起?
- Promise.all in JavaScript: How to get resolve value for all promises? JavaScript中的Promise.all:如何获得所有承诺的解决价值?
- Why Promise.all is undefined 为什么Promise.all未定义
- function will return null from javascript post/get 函数将从javascript post / get返回null
- Use cancel() inside a then-chain created by promisifyAll 在promisifyAll创建的then链中使用cancel()
- Why is it possible to pass in a non-function parameter to Promise.then() without causing an error? 为什么可以在不引起错误的情况下将非函数参数传递给Promise.then()?
- Implement promises pattern 兑现承诺模式
- Promises and performance 承诺与绩效
- Trouble scraping two URLs with promises 刮除带有承诺的两个URL时出现问题
- http.request not returning data even after specifying return on the 'end' event http.request即使在指定了“ end”事件返回后也不会返回数据
- async.each not iterating when using promises 使用promises时async.each不迭代
- jQuery jqXHR - cancel chained calls, trigger error chain jQuery jqXHR-取消链式调用,触发错误链
- Correct way of handling promisses and server response 正确的处理方式和服务器响应
- Return a value from a function call before completing all operations within the function itself? 在完成函数本身内的所有操作之前,从函数调用返回值?
- Resolving a setTimeout inside API endpoint 在API端点内部解析setTimeout
- Async wait for a function 异步等待功能
- JavaScript function that returns AJAX call data 返回AJAX调用数据的JavaScript函数
- try/catch blocks with async/await 使用异步/等待尝试/捕获块
- jQuery Deferred not calling the resolve/done callbacks in order jQuery Deferred没有按顺序调用resolve / done回调
- Returning data from ajax results in strange object 从ajax返回数据会导致奇怪的对象
- javascript - Why is there a spec for sync and async modules? Javascript-为什么有针对同步和异步模块的规范?
#6楼
you can add async option to false and return outside the ajax call. 您可以将async选项添加到false 并在ajax调用之外返回。
function testAjax() {
var result="";
$.ajax({
url:"getvalue.php",
async: false,
success:function(data) {
result = data;
}
});
return result;
}
推荐阅读
-
jQuery:ajax调用成功后返回数据
-
AJAX获取数据成功后的返回数据如何声明成全局变量
-
AJAX获取数据成功后的返回数据如何声明成全局变量
-
javascript - AJAX 成功返回json数据,但是提示500错误。
-
jQuery中ajax请求后台返回json数据并渲染HTML的方法
-
jQuery通过Ajax返回JSON数据_jquery
-
关于jquery ajax 调用带参数的webservice返回XML数据一个小细节_jquery
-
jQuery使用ajax方法解析返回的json数据功能示例
-
jQuery使用ajax方法解析返回的json数据功能示例
-
创建公共调用 jQuery Ajax 带返回值