jQuery jQuery将ajax结果返回到外部变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16805306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:50:41  来源:igfitidea点击:

jQuery return ajax result into outside variable

jqueryajaxvariables

提问by Mohd Shahril

I have some problem using ajax.

我在使用 ajax 时遇到了一些问题。

How can I assign all result from ajax into outside variable ?

如何将 ajax 的所有结果分配给外部变量?

I google it up and found this code..

我用谷歌搜索并找到了这个代码..

var return_first = (function () {
    var tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': "ajax.php?first",
        'data': { 'request': "", 'target': arrange_url, 'method': method_target },
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
});

but not work for me..

但不适合我..

Can anybody tell what is wrong about that code ?

任何人都可以告诉该代码有什么问题吗?

回答by Igor

You are missing a comma after

你后面缺少一个逗号

'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' }

Also, if you want return_firstto hold the result of your anonymous function, you need to make a function call:

此外,如果要return_first保存匿名函数的结果,则需要进行函数调用:

var return_first = function () {
    var tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': "ajax.php?first",
        'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
}();

Note ()at the end.

注意()在最后。

回答by joshuahealy

This is all you need to do:

这就是您需要做的所有事情:

var myVariable;

$.ajax({
    'async': false,
    'type': "POST",
    'global': false,
    'dataType': 'html',
    'url': "ajax.php?first",
    'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
    'success': function (data) {
        myVariable = data;
    }
});

NOTE:Use of "async" has been depreciated. See https://xhr.spec.whatwg.org/.

注意:“异步”的使用已被弃用。请参阅https://xhr.spec.whatwg.org/

回答by Zahra Ghaed

Using 'async': falseto prevent asynchronous code is a bad practice,

使用'async': false来防止异步代码是一种不好的做法,

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. https://xhr.spec.whatwg.org/

主线程上的同步 XMLHttpRequest 已被弃用,因为它会对最终用户的体验产生不利影响。https://xhr.spec.whatwg.org/

On the surface setting async to false fixes a lot of issues because, as the other answers show, you get your data into a variable. However, while waiting for the post data to return (which in some cases could take a few seconds because of database calls, slow connections, etc.) the rest of your Javascript functionality (like triggered events, Javascript handled buttons, JQuery transitions (like accordion, or autocomplete (JQuery UI)) will not be able to occur while the response is pending (which is really bad if the response never comes back as your site is now essentially frozen).

从表面上看,将 async 设置为 false 可以解决很多问题,因为正如其他答案所示,您将数据放入变量中。但是,在等待 post 数据返回时(在某些情况下,由于数据库调用、连接速度慢等,这可能需要几秒钟)其余的 Javascript 功能(如触发事件、Javascript 处理按钮、JQuery 转换(如手风琴或自动完成(JQuery UI))将无法在响应挂起时发生(如果响应永远不会回来,这真的很糟糕,因为您的网站现在基本上被冻结了)。

Try this instead,

试试这个,

var return_first;
function callback(response) {
  return_first = response;
  //use return_first variable here
}

$.ajax({
  'type': "POST",
  'global': false,
  'dataType': 'html',
  'url': "ajax.php?first",
  'data': { 'request': "", 'target': arrange_url, 'method': method_target },
  'success': function(data){
       callback(data);
  },
});

回答by SwiftNinjaPro

'async': falsesays it's depreciated. I did notice if I run console.log('test1');on ajax success, then console.log('test2');in normal js after the ajax function, test2prints before test1so the issue is an ajax call has a small delay, but doesn't stop the rest of the function to get results. The variable simply, was not set "yet", so you need to delay the next function.

'async': false说是贬值了。我确实注意到如果我console.log('test1');在 ajax 上运行成功,然后console.log('test2');在 ajax 函数之后的普通 js 中,test2打印之前,test1所以问题是 ajax 调用有一个小的延迟,但不会停止函数的其余部分以获得结果。变量只是“尚未”设置,因此您需要延迟下一个函数。

function runPHP(){
    var input = document.getElementById("input1");
    var result = 'failed to run php';

    $.ajax({ url: '/test.php',
        type: 'POST',
        data: {action: 'test'},
        success: function(data) {
            result = data;
        }
    });

    setTimeout(function(){
        console.log(result);
    }, 1000);
}

on test.php (incase you need to test this function)

在 test.php 上(以防您需要测试此功能)

function test(){
    print 'ran php';
}

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = htmlentities($_POST['action']);
    switch($action) {
        case 'test' : test();break;
    }
}

回答by borin

I solved it by doing like that:

我通过这样做解决了它:

var return_first = (function () {
        var tmp = $.ajax({
            'type': "POST",
            'dataType': 'html',
            'url': "ajax.php?first",
            'data': { 'request': "", 'target': arrange_url, 'method': 
                    method_target },
            'success': function (data) {
                tmp = data;
            }
        }).done(function(data){
                return data;
        });
      return tmp;
    });
  • Be careful 'async':fale javascript will be asynchronous.
  • 小心 'async':fale javascript 将是异步的。

回答by Andrew

So this is long after the initial question, and technically it isn't a direct answer to how to use Ajax call to populate exterior variable as the question asks. However in research and responses it's been found to be extremely difficult to do this without disabling asynchronous functions within the call, or by descending into what seems like the potential for callback hell. My solution for this has been to use Axios. Using this has dramatically simplified my usages of asynchronous calls getting in the way of getting at data.

所以这在最初的问题之后很久了,从技术上讲,它不是如何使用 Ajax 调用来填充外部变量的直接答案。然而,在研究和响应中,如果不禁用调用中的异步函数,或者降低到回调地狱的可能性,就很难做到这一点。我对此的解决方案是使用Axios。使用它极大地简化了我对异步调用的使用,这些调用妨碍了获取数据。

For example if I were trying to access session variables in PHP, like the User ID, via a call from JS this might be a problem. Doing something like this..

例如,如果我试图通过来自 JS 的调用访问 PHP 中的会话变量,例如用户 ID,这可能是一个问题。做这样的事情..

async function getSession() {
 'use strict';
 const getSession = await axios("http:" + url + "auth/" + "getSession");
 log(getSession.data);//test
 return getSession.data;
}

Which calls a PHP function that looks like this.

它调用了一个看起来像这样的 PHP 函数。

public function getSession() {
 $session = new SessionController();
 $session->Session();
 $sessionObj = new \stdClass();
 $sessionObj->user_id = $_SESSION["user_id"];
 echo json_encode($sessionObj);
}

To invoke this using Axios do something like this.

要使用 Axios 调用它,请执行以下操作。

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
});

The result would be, in this case a Json object from PHP.

在这种情况下,结果将是来自 PHP 的 Json 对象。

{"user_id":"1111111-1111-1111-1111-111111111111"}

Which you can either use in a function directly in the response section of the Axios call or set a variable or invoke another function.

您可以直接在 Axios 调用的响应部分中的函数中使用它,也可以设置变量或调用另一个函数。

Proper syntax for the Axios call would actually look like this.

Axios 调用的正确语法实际上是这样的。

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
}).catch(function (error) {
 console.log(error);
});

For proper error handling.

为了正确的错误处理。

I hope this helps anyone having these issues. And yes I am aware this technically is not a direct answer to the question but given the answers supplied already I felt the need to provide this alternative solution which dramatically simplified my code on the client and server sides.

我希望这可以帮助任何有这些问题的人。是的,我知道这在技术上不是问题的直接答案,但鉴于已经提供的答案,我觉得有必要提供这种替代解决方案,它极大地简化了我在客户端和服务器端的代码。