簡體   English   中英

Javascript if else語句不適用於JSON

[英]Javascript If else statement not working with JSON

我有以下代碼。 因此,基本上,JavaScript需要查看用戶名和密碼,並通過API(有效)進行檢查,並返回true或false。 設置為true授予用戶訪問下一頁的權限,設置為false則重新加載登錄頁面的權限。

除了JavaScript if語句外,其他所有東西都可以正常運行。
我的代碼如下:

var ApiKey = '';  //generated API Key
var userPass = document.getElementById('pass');  //gets the password
var userName = document.getElementById('usr');   //gets the username

function testAJAX(){
$.getJSON("http://mywebsitesapiaddress.com/api" + ApiKey +"&user="+ userName.value + "&pass=" + userPass.value, function(data) {
    if (data.success == "true") {
        window.location = "mainpage.html";
    }
    else {
      location.reload();
    }
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<input type="text" name="username" id="usr" placeholder="Enter your username">
<input type="password" name="password" id="pass" placeholder="Enter your password">
<button onclick="testAJAX()" id ="login">Login</button>  

除了success屬性值的類型之外,您的代碼看起來還不錯。

服務器可能未返回字符串文字'true'而是返回布爾值true因此

if (data.success) { //or data.success === true
  window.location = "mainpage.html";
} else {
  location.reload();
}

JSON數據為true或false時。 不能使用雙引號。

感謝您的快速回復。 原來問題是數據類型沖突,我將API響應更改為1和0,這似乎已經解決了問題。 使用數字時更輕松,更靈活。

var ApiKey = '';  //generated API Key
var userPass = document.getElementById('pass');  //gets the password
var userName = document.getElementById('usr');   //gets the username

function testAJAX(){
$.getJSON("http://mywebsitesapiaddress.com/api" + ApiKey +"&user="+ userName.value + "&pass=" + userPass.value, function(data) {
    if (data.success == 1) {
        window.location = "mainpage.html";
    }
    else {
      location.reload();
    }
});
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM