简体   繁体   English

一个函数内的jQuery ajax请求:如何返回我得到的值?

[英]JQuery ajax request inside a function: how to return the value I got?

I want to write a javascript function, that will make an ajax request to PHP script and returns it's result. 我想编写一个javascript函数,该函数将向PHP脚本发出ajax请求并返回其结果。 That's how it looks: 看起来就是这样:

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

The problem is, that result is always undefined. 问题是, result始终是不确定的。 This might be because variable result is not in myjsfunc namespace? 这可能是因为变量result不在myjsfunc命名空间中? 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? 有办法吗?

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. 您的AJAX调用是异步发生的,并且在POST发生后会调用回调函数。 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);
            }
        }
    );
}

Where you'll define myReturnHandler separately and it will need to know how to take over processing with the result data. 在单独定义myReturnHandler的位置,它将需要知道如何接管结果数据的处理。

-- EDITED -- -编辑-

You can also perform tests to determine how to handle your response. 您还可以执行测试以确定如何处理响应。 Added extra code to demonstrate. 添加了额外的代码来演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM