简体   繁体   English

变量在 ajax 后出现空白,但在 ajax 成功函数中具有值

[英]variable appearing blank after ajax, but has value within ajax success function

As the title says, I have an ajax function that I am using to call a function that assigns a value to a variable in js from my mysql db.正如标题所说,我有一个 ajax 函数,我用它来调用一个函数,该函数为我的 mysql 数据库中的 js 变量赋值。 On success, I can print the echoed data out and it appears in the console fine.成功后,我可以打印出回显的数据,它会很好地显示在控制台中。 However, calling the variable after the ajax call yields an empty variable.但是,在 ajax 调用之后调用该变量会产生一个空变量。 What is going on?到底是怎么回事?

Code below:代码如下:

request = $.ajax({ 
                        url: "/fans/get_url_tag", 
                        type: "post", success:function(data){url_tag = data; console.log(url_tag); //prints the correct value}, 
                        data: {'fbid': result.id} ,beforeSend: function(data){console.log(data);} 
                    });

//prints nothing
console.log(url_tag)

Sounds like the scope is wrong.听起来范围是错误的。 Maybe just declare it before your $.ajax call:也许只是在你的 $.ajax 调用之前声明它:

var url_tag;
request = $.ajax({ 
                    url: "/fans/get_url_tag", 
                    type: "post", success:function(data){url_tag = data; console.log(url_tag);}, 
                    data: {'fbid': result.id} ,beforeSend: function(data){console.log(data);} 
                });

console.log(url_tag); //Should print the same value

您需要将console.log放在回调函数中。

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

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