2012-04-28 72 views
2

我使用的是下面JSON调用在我的JavaScript方法等待的Json调用完成在JavaScript

function go123(){ 
    var cityName = ""; 
    var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) { 
     if (data.properties.city != null){ 
      cityName = data.properties.city; 
      check = true; 
     } else { 
      cityName = "NaN" 
     } 
    }); // end of my Json Call. 

    // my validation is done below 
    if(cityName != "NaN"){ 
     return false; 
    } else { 
    // here I except the cityName to not be "" but be some value which is set as :cityName = data.properties.city; 
     return true; 
    } 
} // end of my function 

现在是什么问题,我面对的是,在我的Json调用compelete下一个已经执行了一组语句(在“//我的验证在下面完成”一行下面的代码中)。

我想在我的JSON调用(的cityName)设置的值,只有一次是当通话结束,然后我只想要执行的语句的下一组。

请帮我解决这个问题。任何意见/想法/建议将不胜感激!谢谢。

回答

3

AJAX调用是asyncrhonous。他们不等待答复。它们在后台运行并在调用后立即执行紧随其后的代码。因此,在getJSON接收到的数据还没有出现在它下面的操作执行时。

你可以把你想要的操作回调,这样,当数据被revceived他们得到执行:

function go123(callback){ 
    var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) { 
     //execute the callback, passing it the data 
     callback(data); 
    }); 
} 

//when you call go123, it get's back the result: 
function goBefore123(){ 

    //get our JSON 
    go123(function(data){ 

     //when we get our data, evaluate 
     if (data.properties.city != null){ 

      cityName = data.properties.city; 
      check = true; 

      alert('executed after returned'); 
      afterCall(); 
     } else { 
      cityName = "NaN" 
     } 
    }); 

    alert('i am executed before anything else'); 
} 

function afterCall(){ 
    alert('im also executed after'); 
} 
+0

哇,看上去很不错,让我尝试了这一点,现在 – Yasser 2012-04-28 08:16:36

+0

的go123(函数(结果),你所写的功能那是什么么?它应该以分号结束? – Yasser 2012-04-28 08:19:49

+0

@Yasser的'go123(函数(结果){ ...})'调用'go123()'函数,它传递的是被执行一次'getJSON'接收它的答复“回调”功能。是的,应该有一个';'这是可选的电话后, – Joseph 2012-04-28 08:22:29

4

你传递到$ .getJSON函数()是回调运行时函数成功地完成。所有其他条件相同的情况下,请在该方法内粘贴“其余部分”。如果你不能这样做,那么你之后被称为jQuery Deferred。代码看起来像这样见http://www.erichynds.com/jquery/using-deferreds-in-jquery/http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

var req = $.getJSON('blah', 'de', 'blah'); 

req.success(function(response){ 
    // The request is done, and we can do something else 
}); 
+0

我希望主函数返回一个“真”或“假”,这似乎并没有在里面工作成功的方法。这是可能的还是我犯了一个错误(而编码)实现这种 – Yasser 2012-04-28 08:05:33

+0

这是不礼貌的同步等待异步方法。您的主要功能可以返回延期,并且呼叫者也可以订阅其完成。 – robrich 2012-04-28 17:14:10

1

调用外部URL会花费太多时间,等待结果 检查以下

var jqxhr = $.getJSON("example.json", function() { 
    alert("success"); 
}) 
.success(function() { alert("second success"); }) 
.error(function() { alert("error"); }) 
.complete(function() { alert("complete"); }); 

http://api.jquery.com/jQuery.getJSON/

+0

我想让主函数返回'true'或者'true' '假',这似乎不成功的成功方法。这是可能的还是我犯了一个错误(编码时)实现这一点 – Yasser 2012-04-28 08:18:31