在JavaScript代码中的if块之外访问变量的更改值时出现问题 [英] Problem in accessing a variable's changed value outside of if block in javascript code

查看:111
本文介绍了在JavaScript代码中的if块之外访问变量的更改值时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$("#submit").click(function(){
        var query=getquerystring() ; //get the query string entered by user
        // get the JSON response from solr server 
        var newquery=query;

    $.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&json.wrf=?", function(result){
            //$.each(result.response.docs, function(result){

                if(result.response.numFound==0)
                {

                $.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&spellcheck=true&json.wrf=?", function(result){


                    $.each(result.spellcheck.suggestions, function(i,item){
                        newquery=item.suggestion;

                    });

                });

                }

在上面的javascript代码中,变量newquery初始值具有查询值.但是,如果if条件为true,则其值已更改.但是我的问题是我想获得更改后的值时,无法在if块之外获取其更改后的值.我该怎么办.

In the above javascript code a variable newquery initialy having value of query. but when the if condition is true its value have changed. but my problem is i am not getting its changed value outside of if block while i want this changed value. how can i do this.

请回复.

编辑

我可以这样做吗:

   $.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&json.wrf=?"
  {
  async:false
  }, 
function(result) {

推荐答案

问题是$ .getJson是异步的.

The problem is that $.getJson is asynchron.

查看此内容:

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆