【问题标题】:jsonpCallback scope troublejsonpCallback 范围问题
【发布时间】:2017-01-05 16:45:19
【问题描述】:

我是 Web 开发的菜鸟,在以下代码中分配 myCountry 变量时遇到问题:

 <html>
 <head>
<script>
var myCountry=" "
function jsonpCallback(data) { 
           myCountry=data.address.country;
            }
jsonpCallback();
var countryText="You are from "+myCountry;
        document.getElementById("displaycountry").innerHTML =countryText;
}
</script>
<script src="http://api.wipmania.com/jsonp?callback=jsonpCallback"
                 type="text/javascript">
                 </script>
</head>
<center>
<p id="displaycountry" ></p>
</body>
</html>

我想将 data.address.country 的值分配给 myCountry 并在函数之外使用它,但该值始终保持为“”。

如果我使用以下代码,jsonpCallback 函数可以很好地显示国家(但我希望能够在 html 中修改它的位置):

function jsonpCallback(data) { 
          a.innerHTML ="<br/>Country: " + data.address.country; 

            }

谢谢

【问题讨论】:

  • 问题不在于您的 JSONP 回调,而在于您不了解该调用的异步性质。您从myCountry 分配的内容刚刚过早,因此之前的回调来不及执行。

标签: json variables scope country


【解决方案1】:

正如@Sirko 提到的,问题在于您实际上并没有调用 Wipmania api,而是试图将回调用作 QueryString 参数,这将无法通过简单地将请求放在 @987654322 上@标签。

这就是您可能想要做的事情。

首先,您需要更改回调函数的标签,因为它将在请求检索到任何数据后执行:

<p id="displaycountry"></p>

<script>
var myCountry = "";

// This is your callback function
function jsonCallback(data) { 
  myCountry = data.address.country;
  var countryText="You are from "+myCountry;
  document.getElementById("displaycountry").innerHTML = countryText;
}

// Do the request
// Code below
</script>

接下来您要做的实际上是调用 api,可能使用 Javascript 本身的 XMLHttpRequest

// This will stablish the Request to the api
var xmlhttp = new XMLHttpRequest();
var url = "//api.wipmania.com/json";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var response = JSON.parse(xmlhttp.responseText);
        jsonCallback(response);
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

希望对您有所帮助,对于 Javascript 的更多基础知识,我推荐一些在线速成课程,也许 Codecademy 是一个不错的起点。

干杯

【讨论】:

    猜你喜欢
    • 2014-12-28
    • 1970-01-01
    • 2020-03-04
    • 2010-11-09
    • 2011-01-08
    • 2011-04-09
    • 2016-08-04
    • 2014-04-09
    相关资源
    最近更新 更多