为什么我不能从$ .post(jquery)返回数据 [英] why cant I return data from $.post (jquery)

查看:168
本文介绍了为什么我不能从$ .post(jquery)返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

function test(){

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

}

var foo = test()
alert(foo)

它说foo是未定义的.但是,即使在我这样做时,也要更进一步:

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

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)

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

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

谢谢

推荐答案

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

$.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.

所以您可以做的是代替返回,而使用回调函数并在外部定义回调函数.

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

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
}

这篇关于为什么我不能从$ .post(jquery)返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆