使用全局变量在javascript中通过函数获取值

时间:2014-02-20 13:13:11

标签: javascript

var voted;

$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){
  voted = data.host;
  console.log(voted);
});

console.log(voted);

所以votedundefined之外,但是,它在函数内部正确定义。

我想知道如何在函数外部使用data.value。我唯一能想到的是使用全局变量,然而,它不能按预期工作。

编辑:在功能之外需要IP

$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){
  voted(data.host);
});

function voted(ip) {
  ip_voted = ip_array.indexOf(ip);

  if (ip_voted > -1) {
    window.location.href = "results";
  }
}


if (choice && ip == '123123123') {

}

2 个答案:

答案 0 :(得分:0)

你可以这样使用

$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){

      writeVoted(data.host);
});

function writeVoted(voted) {
    console.log(voted);
}

或留下同步电话(我认为不可取)

async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default).      If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

答案 1 :(得分:0)

它无法解决的原因是对getJSON的调用是异步调用。从某种意义上说,它意味着它被撕掉了当前的流程并在某个地方独立执行。请查看我在下面的代码中添加的评论:

var voted;

//getJSON is executed right away - async
$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){
  //This callback function executes when the remote request responds. The timeframe is variable.
  voted = data.host;
  console.log(voted);
});

//Gets executed right away - doesn't wait for getJSON to get the remote response.
//voted is probably still undefined.
console.log(voted);

您需要添加一个继续流程的功能,如下所示:

$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){
    voted(data.host);
});

function voted(ip) {
  ip_voted = ip_array.indexOf(ip);

  if (ip_voted > -1) {
    window.location.href = "results";
  }

   verify(ip);
}

function verify(ip) {
    if (choice && ip == '123123123') {

    }
}

如果你真的需要在全局变量中使用数据,你可以“等待”响应 - 但是我强烈建议不要这样做:

var host, value;
var responseArrived = false;

$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){
     host = data.host;
     value = data.value;
     responseArrived = true;
});

while( !responseArrived ) {
   //NOT A GOOD IDEA!
   //Will continue to loop until the callback of getJSON is called.
   //NOT A GOOD IDEA!
}

console.log(host);
console.log(value);