javascript 在 AJAX 函数中声明变量并稍后调用 (jQuery)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18771922/
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-10-27 13:11:14  来源:igfitidea点击:

Declaring Variable within AJAX function and Calling It Later (jQuery)

javascriptjqueryajax

提问by MillerMedia

I've got an AJAX function that works correctly but I can't seem to access variables that I'm declaring within the function later in the page. If you look at the below code, you'll see I alert the variable number_rows within the function which works but when I try to log it outside of the function, it comes back as 'undefined.'

我有一个可以正常工作的 AJAX 函数,但我似乎无法访问我在页面后面的函数中声明的变量。如果您查看下面的代码,您会看到我在函数中提醒变量 number_rows 起作用,但是当我尝试将其记录到函数之外时,它返回为“未定义”。

var newData = "user_id=" + id;

    $.ajax({
        type: 'POST', // HTTP method POST or GET
        url: 'ajax.php', //Where to make Ajax calls
        dataType:'text', // Data type, HTML, json etc.
        data:newData, //post variables
        success:function(response){

            var number_rows = response;
           alert(number_rows);

        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
        }
    });

console.log(number_rows);

I understand my scope may be off. I tried to move all of my code within the success function but that causing a bunch of other issues so the easiest thing would be to get the response variable to be a global variable that I could use throughout the rest of the page's code. I also tried something like this:

我了解我的范围可能已关闭。我试图在成功函数中移动我的所有代码,但这会导致一系列其他问题,所以最简单的方法是让响应变量成为一个全局变量,我可以在页面的其余代码中使用它。我也尝试过这样的事情:

success:function(response){

        $('body').append('<span class="ajax_response" id="' + response + '"></span>');

    }

var number_rows = $('.ajax_response').attr('id');
console.log(number_rows);

But for some reason it isn't able to pick up the ID value immediately that way. I can confirm that the span does get made with the correct ID value but for some reason it doesn't handle it correctly. Any help with this would be greatly appreciated.

但是由于某种原因,它无法立即以这种方式获取 ID 值。我可以确认 span 确实使用正确的 ID 值制作,但由于某种原因它没有正确处理它。对此的任何帮助将不胜感激。

Thanks!

谢谢!

回答by sudhAnsu63

Changed the scope of your variable.
Change async: falseor wait till you get the response from server, then use the value.

更改了变量的范围。
更改async: false或等到您从服务器获得响应,然后使用该值。

var newData = "user_id=" + id;
var number_rows = "";  //Declare Here

    $.ajax({
        type: 'POST', // HTTP method POST or GET
        url: 'ajax.php', //Where to make Ajax calls
        dataType:'text', // Data type, HTML, json etc.
        data:newData, //post variables
        async: false,
        success:function(response){

            number_rows = response;  //assign here
           alert(number_rows);

        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
        }
    });

console.log(number_rows);  //Use here

回答by loddn

Yes, your scope is off. If you defining a variable inside a function, as you do, you cannot access it outside. Also your ajax call is async and any code you.

是的,您的范围已关闭。如果你在函数内部定义一个变量,就像你所做的那样,你不能在外部访问它。此外,您的 ajax 调用是异步的,您可以使用任何代码。

Put your console.log inside the success function otherwise it will probably log undefined even if you declare the variable globally outside of the function.

将您的 console.log 放在成功函数中,否则即使您在函数外部全局声明变量,它也可能会记录 undefined 。

var newData = "user_id=" + id;
var number_rows;
$.ajax({
    type: 'POST', // HTTP method POST or GET
    url: 'ajax.php', //Where to make Ajax calls
    dataType:'text', // Data type, HTML, json etc.
    data:newData, //post variables
    success:function(response){
        number_rows = response;
        alert(number_rows);
        console.log(number_rows); // here, so we are sure it's set. 
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
        }
    });

回答by Leo

Just add to your configuration:

只需添加到您的配置中:

async:false

Your code maybe look like this:

您的代码可能如下所示:

var newData = "user_id=" + id;
var number_rows = ""; //This is a global variable

    $.ajax({
        type: 'POST', 
        url: 'ajax.php',
        dataType:'text', 
        data:newData,
        async:false, //<------This is the option you must add
        success:function(response){

            number_rows = response;  //<----- receive data from the server
           alert(number_rows);

        },
        error:function (/*stuff here*/){
            //stuff here
        }
    });

  //Check data
   console.log(number_rows); 

Good luck ^^!

祝你好运^^!