Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

javascript - 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; 
}
  ask by Francesco translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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中工作:)

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是一个很好的函数抽象:我无法返回数据,因为我还没有数据,并且我不想阻塞并让您等待,所以这是一个诺言 ,您将能够以后使用它,或仅将其提供给其他人并完成它。)

See this DEMO .

(看到这个演示 。)

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 <a href="https://stackoom.com/link/aHR0cHM6Ly9kZXZlbG9wZXIubW96aWxsYS5vcmcvZW4tVVMvZG9jcy9XZWIvSmF2YVNjcmlwdC9SZWZlcmVuY2UvR2xvYmFsX09iamVjdHMvUHJvbWl


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...