使用JQuery POST的Javascript函数总是返回未定义的 [英] Javascript Function With JQuery POST Always Returns undefined

查看:142
本文介绍了使用JQuery POST的Javascript函数总是返回未定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这里发生了什么,希望有人能帮上忙,我肯定这件事很容易发生,我只是想念。



我在JavaScript中有一个函数,里面有一个JQuery文章。我想返回只是文本的帖子的结果并将其放入一个变量中。这个数字是从Post正确回来的,但是当我把它放在变量中时,变量就会显示undefined。任何想法?

  var total = GetTotalSize(); 
alert(total);

函数GetTotalSize(){
var i =;
$ .post(Handlers / GetTotal.ashx,{id:$(#hID)。val()},function(data){
i = data.toString();
返回i;
});


解决方案

您无法做到像那样。请记住,AJAX中的A表示异步。在 GetTotalSize()执行并返回后,您提供给 $。post()的回调函数将很好地执行。 p>

您需要重构代码以适应此情况。我不能确定我的建议,因为我不知道代码的其余部分是什么样子,但这是一种可能性。

 <$ c $($ Handler / GetTotal.ashx),{id:$(#hID)。val()},function(data)
{
doSomethingWithTotalSize(data.toString( ));
});

函数doSomethingWithTotalSize(totalSize)
{
//无论
}


I have no idea what's going on here and was hoping someone could help, I'm sure it's something easy going on that I'm just missing.

I have a function in javascript that has a JQuery post inside of it. I would like to return the results of the post which is just text and put it in a variable. The number is coming back correctly from the Post but when I put it in the variable, the variable says "undefined". Any ideas?

var total = GetTotalSize();
alert(total);

function GetTotalSize(){
    var i = "";
    $.post("Handlers/GetTotal.ashx", {id : $("#hID").val()}, function(data){
        i = data.toString();
        return i;
    });
}

解决方案

You can't do it like that. Remember, the "A" in AJAX means "Asynchronous". The callback function you provide to $.post() will execute well after GetTotalSize() executes and returns.

You'll need to restructure your code to accommodate this. I can't be specific in my recommendation because I don't know what the rest of your code looks like, but here's a possibility.

$.post("Handlers/GetTotal.ashx", {id : $("#hID").val()}, function(data)
{
  doSomethingWithTotalSize( data.toString() );
});

function doSomethingWithTotalSize( totalSize )
{
  // whatever
}

这篇关于使用JQuery POST的Javascript函数总是返回未定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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