繁体   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