简体   繁体   English

将ajax请求结果分配给jquery函数中的变量

[英]Assign ajax request result to variable in the jquery function

I am trying to assign value I receive from the php file to the jquery variable. 我试图将我从php文件收到的值分配给jquery变量。 The php file runs a loop and echos out a value. php文件运行一个循环并回显一个值。 I am trying then to store the value in the jquery variable but I am getting NaN result back. 我试图然后将值存储在jquery变量中,但是我得到了NaN结果。 How can I assign the value echoed from the php file into the variable in the jquery function? 如何将从php文件回显的值分配给jquery函数中的变量?

    var increment;

    event.preventDefault();
    $.ajax({
            type: 'POST',
            url: 'increment.php',
            data: $(this).serialize(),
            dataType: 'text',
            success: function (data) {
                    //console.log(data);
                    data = increment;
            }
    });

You should be using 您应该使用

increment = data;

instead of 代替

data = increment;

Also one more thing to note here is the request nature. 这里还要注意的另一件事是请求性质。 Since the ajax request is asynchronous accessing the variable outside might show unexpected result. 由于ajax请求是异步访问的,因此,外部变量可能会显示意外结果。 You have to access the variable once the ajax request is successful (inside success callback). 一旦ajax请求成功(在成功回调内部),您就必须访问变量。

do like so,you should assign data recieved to increment var: 这样做,您应该分配接收到的数据以使var递增:

    var increment;

event.preventDefault();
$.ajax({
        type: 'POST',
        url: 'increment.php',
        data: $(this).serialize(),
        dataType: 'text',
        success: function (data) {
                //console.log(data);
                increment = data ;
        }
});

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

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