在函数内部JQuery的Ajax请求:如何返回我的价值? [英] JQuery ajax request inside a function: how to return the value I got?

查看:117
本文介绍了在函数内部JQuery的Ajax请求:如何返回我的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个JavaScript函数,这将使一个Ajax请求的PHP脚本,并返回它的结果。这就是它的外观:

I want to write a javascript function, that will make an ajax request to PHP script and returns it's result. That's how it looks:

function myjsfunc(some_data)
{
    $.post(
            "/myscript.php",
            { some_data: some_data },
            function(response)
            {
                result = response;
            }
          );
    return result;
}

现在的问题是,该结果总是不确定的。这可能是因为变量结果不是 myjsfunc 命名空间?或者是因为成功的功能,结果收到的主要功能是处理后的方式?

The problem is, that result is always undefined. This might be because variable result is not in myjsfunc namespace? Or it is because success function result is received way after the main function is processed?

不管怎样,我怎样才能得到想要的结果?有什么办法?

Anyway, how can I get desired result? Is there a way?

推荐答案

您不明白,因为它不是由你的外在功能完成的时间定义为返回的结果。您的AJAX调用正在发生异步回调函数被称为后发生之后。为了对付你的结果,你需要做的是这样的:

You don't get to return the result because it's not defined by the time your outer function finishes. Your AJAX call is happening asynchronously and the callback function is being called after the POST happens. To deal with your result, you need to do something like this:

function myjsfunc(some_data) {
    $.post("/myscript.php", { some_data: some_data }, function(response) {
            if (some_data.prop) {
                myReturnHandler(response);
            } else {
                myOtherHandler(response);
            }
        }
    );
}

在这里您可以分别定义myReturnHandler,它将需要知道如何接手处理的结果数据。

Where you'll define myReturnHandler separately and it will need to know how to take over processing with the result data.

- EDITED -

-- EDITED --

您也可以进行测试,以确定如何处理你的回应。添加了额外的code证明。

You can also perform tests to determine how to handle your response. Added extra code to demonstrate.

这篇关于在函数内部JQuery的Ajax请求:如何返回我的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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