2016-11-29 127 views
0

我在那里,我创造了一些验证表单时,和验证的一个需要从输入抢值,并在JSON文件,如果在我的情况下,检查服务器上价值存在。重定向到另一个通风口有一个返回前

唯一的问题是,即使它存在并进入返回状态,正在重定向,我不知道promise是否与它有关。

我的代码是这样的:

$("#btnclick").click(function(){ 

    $.getJSON("locations.json", function(json) { 

     var locations = _.filter(json, function(o) { 
      return o.value == $originLocation; 
     }); 

     if(locations.length <=0){ 
      console.log("doesnt exist this location origin"); 

      //stop here 
      return; 
     }else{ 
      console.log("Yes it exist"); 

     } 

    }); 


    window.location = "some link.php"; 

    // go to another link--> redirect 

}); 

回答

0

我认为一旦你重新格式化你的代码中的错误会更加明显:

$("#btnclick").click(function() { 
    $.getJSON("locations.json", function(json) { 
     var locations = _.filter(json, function(o) { 
      return o.value == $originLocation; 
     }); 

     if (locations.length <=0) { 
      console.log("doesnt exist this location origin"); 
      //stop here 
      return; 
     } else { 
      console.log("Yes it exist");  
     }   
    }); 

    window.location = "some link.php"; 
    // go to another link--> redirect 

}); 

window.location的总是被调用的点击。使用一个承诺链 我想什么你想在这里做的是:

$("#btnclick").click(function() { 
    $.getJSON("locations.json", function(json) { 
     var locations = _.filter(json, function(o) { 
      return o.value == $originLocation; 
     }); 

     if (locations.length <=0) { 
      console.log("doesnt exist this location origin"); 
      //stop here 
      return Promise.resolve(true); 
     } else { 
      console.log("Yes it exist");  
      return Promise.resolve(true); 
     }   
    }).then(exists) { 
     if (exists) { 
      window.location = "some link.php"; 
     } 
    } 
}); 
+0

感谢您的答复,但没有把window.location的里面的方法吗?由于代码会影响其他代码 – Pedro

+0

请参阅更新。那么你需要使用某种承诺链。 – Shaun