【问题标题】:Declaring global variable inside jquery .get method [duplicate]在jquery .get方法中声明全局变量[重复]
【发布时间】:2017-05-13 10:12:04
【问题描述】:

无法在此 jquery 方法中声明全局变量。我缺少什么以及如何做?

var info = "empty";
 
$.get("http://ip-api.com/json", function(response) {
	 info = response.city;
 }, "jsonp");
 
 console.log(info);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【问题讨论】:

  • $.get 是异步方法,因此您的console.log 将显示初始值。将console.log 放入$.get 中,您将看到更新后的值,

标签: javascript jquery scope get


【解决方案1】:

你可以像这样设置变量

var info = "";

$(document).ready(function(){
    $.get("http://ip-api.com/json", function(response) {
        info = response.city;
        console.log(info);
    }, "jsonp");
}); 

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 2018-08-06
    • 2021-02-17
    • 2020-10-12
    • 2014-02-12
    相关资源
    最近更新 更多