2016-11-29 114 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