为什么我不能从 $.post (jquery) 返回数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16987811/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:12:55  来源:igfitidea点击:

why cant I return data from $.post (jquery)

jquerypost

提问by Sam Creamer

I must be making a silly mistake but I cannot return the data I get from a $.post function and store it in a variable, not only that, I cannot return ANYTHING from within that function. Example:

我一定犯了一个愚蠢的错误,但我无法返回从 $.post 函数获得的数据并将其存储在变量中,不仅如此,我无法从该函数中返回任何内容。例子:

function test(){

$.post("demo_test_post.asp",
    {
      name:"Donald Duck",
      city:"Duckburg"
    },
    function(data,status){
      return(data)
    });

}

var foo = test()
alert(foo)

it say's that foo is undefined. But to take it a step further, even when I do this:

它说 foo 是未定义的。但更进一步,即使我这样做:

function test(){

    $.post("demo_test_post.asp",
        {
          name:"Donald Duck",
          city:"Duckburg"
        },
        function(data,status){

          var bar = "bar"
          return(bar)
        });

    }

    var foo = test()
    alert(foo)

it STILL says foo is undefined... I must be doing something wrong or misunderstanding something. Can someone please help.

它仍然说 foo 是未定义的......我一定是做错了什么或误解了什么。有人可以帮忙吗。

Thanks

谢谢

回答by Nagarjun

$.post is a asynchronous function. The control from function will immediately return after it run post but the response from post may be received later.

$.post 是一个异步函数。来自函数的控件在运行 post 后将立即返回,但可能稍后会收到来自 post 的响应。

So what you can do is instead of return, use a call back function and define callback function outside.

所以你可以做的不是返回,而是使用回调函数并在外部定义回调函数。

say,

说,

function test(){

  $.post("demo_test_post.asp",
    {
      name:"Donald Duck",
      city:"Duckburg"
    },
    function(data,status){
      my_function(data)
    });

}

function my_function(data){
  // you can operate on data here
}

回答by CodingIntrigue

You don't return anything from post(). What you have inside function(data, status) {}is actually a callback and doesn't return a result to the post()method like you think.

你不会从 返回任何东西post()。你里面function(data, status) {}的东西实际上是一个回调,不会post()像你想象的那样将结果返回给方法。

Have a read of the this articlefor more information

阅读这篇文章了解更多信息

回答by Tim B James

A jQuery post()is by default Asynchronousmeaning that you can never return a value from a function like this.

post()默认情况下,jQuery是异步的,这意味着您永远无法从这样的函数中返回值。

To Quote the jQuery Docs

引用jQuery 文档

async(default: true)

Type: Boolean

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

异步(默认值:true)

类型:布尔型

默认情况下,所有请求都是异步发送的(即默认设置为 true)。如果您需要同步请求,请将此选项设置为 false。

You would need to provide a callback function in order to update the value.

您需要提供回调函数才能更新值。

e.g. A very basic example.

例如一个非常基本的例子。

var foo;
test();    

function test(){    
    $.post("demo_test_post.asp",
        {
          name:"Donald Duck",
          city:"Duckburg"
        },
        function(data,status){

          var bar = "bar"
          foo = bar; // assign foo

        });    
    }    
}

Alternatively you can look at changing your jQuery Ajax to be Synchronous. Take a look at this post here How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

或者,您可以考虑将 jQuery Ajax 更改为Synchronous。在此处查看这篇文章如何让 jQuery 执行同步而不是异步的 Ajax 请求?

回答by Dylan N

Try using the .done() to execute the returned data. This should ensure that it gets the data and doesn't set your variable or alert data before it finishes.

尝试使用 .done() 来执行返回的数据。这应该确保它获取数据并且在完成之前不会设置您的变量或警报数据。

$.post("demo_test_post.asp", { name: "Donald Duck", city: "Duckburg" })
.done(function(data) {
  alert("Data Loaded: " + data);
  //Or return data;
});

回答by Annabelle

jQuery AJAX requests are made asynchronously, meaning that the request is started and the $.post()method returns more or less immediately. The request is processed by the browser in the background. When the request is completed, jQuery calls the callback function you supplied to $.post(). You can use async: falseto tell jQuery to block until the request completes, but this is not recommended as it will almost certainly result in terrible performance and a poor user experience.

jQuery AJAX 请求是异步发出的,这意味着请求已启动并且该$.post()方法或多或少会立即返回。请求由浏览器在后台处理。请求完成后,jQuery 会调用您提供给 的回调函数$.post()。您可以使用async: false告诉 jQuery 阻塞直到请求完成,但不推荐这样做,因为它几乎肯定会导致糟糕的性能和糟糕的用户体验。

What you should do instead is write your code such that the logic that depends on the AJAX response is kicked off by your callback function. Something like:

相反,您应该做的是编写代码,使依赖于 AJAX 响应的逻辑由您的回调函数启动。就像是:

function handleAjaxResponse(responseData) {
  // do something with the response.
}

function doAjax() {

  $.post("demo_test_post.asp",
    {
      name:"Donald Duck",
      city:"Duckburg"
    },
    function(data, status){
      handleAjaxResponse(data);
    });

}

doAjax();

回答by cssyphus

You are using the more streamlined .post()method. This is both more finicky to work with (IMHO) and somewhat less powerful than the larger form, $.ajax().

您正在使用更精简的.post()方法。与较大的形式$.ajax().

Personally, I have found the .ajax()method to be preferable because the added structure makes it easier to format. Also, you can do more with .ajax(there are more options, such as turning off asynch which is sometimes very useful when you want to delay processing until the data has been returned).

就个人而言,我发现该.ajax()方法更可取,因为添加的结构使其更易于格式化。此外,您可以做更多事情.ajax(有更多选项,例如关闭异步,这在您想要延迟处理直到数据返回时有时非常有用)。

Here is a simple exampleof using the full $.ajax()method. Note the successfunction at the bottom -- that is where you can use the data sent back from the other PHP file!

这是使用完整$.ajax()方法的简单示例。请注意success底部的函数——您可以在此处使用从其他 PHP 文件发回的数据!