将数据存储在来自jquery的变量中 [英] Store data in variable from post jquery

查看:99
本文介绍了将数据存储在来自jquery的变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

function someFunction(something1, something2) {

    $.post("execute.php", { someData1: something1, someData2: something2 }, function(data) {

        returnData = data;

    });

    return returnData;

}

Post函数返回false或true,我希望此someFunction通过返回值进一步发送此信息,但是它不起作用.我猜想这个返回值在发布之前就返回了,所以没有定义,但是我不知道该怎么做.

解决方案

ajax调用是异步的,这意味着它不影响运行".该函数将立即执行并返回,而javascript则以其愉快的方式继续运行,而ajax调用则以非常规方式"执行.

这就是为什么它返回undefined的原因,因为它不是.

要防止此行为,您需要将其设置为"synchronous".并且您需要在函数范围之外定义returnData.

您可以通过设置来实现

$.ajaxSetup({async:false});

然后调用$ .post,

或者您可以执行$.ajax(... {async:false}...);

所以使用第一种方法:

function someFunction(something1, something2) {
    $.ajaxSetup({async:false});  //execute synchronously

    var returnData = null;  //define returnData outside the scope of the callback function

    $.post("execute.php", { someData1: something1, someData2: something2 }, function(data) {

        returnData = data;

    });

    $.ajaxSetup({async:true});  //return to default setting

    return returnData;

}

I've got this code:

function someFunction(something1, something2) {

    $.post("execute.php", { someData1: something1, someData2: something2 }, function(data) {

        returnData = data;

    });

    return returnData;

}

Post function returns either false or true and I want this someFunction send this information further by return value, but it doesn't work. I'm guessing this return value returns before it posts so there's undefined, but I have no idea what to do about it.

解决方案

The ajax call is asynchronous, meaning it runs 'out of the way'. The function is executed and returned immediately and javascript continues on its merry way, while the ajax call is executed 'out of the way'.

That is why it is returning undefined, because it isn't.

To prevent this behavior you need to set it to 'synchronous'. And you need to define returnData outside the scope of the function.

You can either do this by setting

$.ajaxSetup({async:false});

And then calling $.post,

Or you can do $.ajax(... {async:false}...);

So using the first method:

function someFunction(something1, something2) {
    $.ajaxSetup({async:false});  //execute synchronously

    var returnData = null;  //define returnData outside the scope of the callback function

    $.post("execute.php", { someData1: something1, someData2: something2 }, function(data) {

        returnData = data;

    });

    $.ajaxSetup({async:true});  //return to default setting

    return returnData;

}

这篇关于将数据存储在来自jquery的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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