简体   繁体   English

Javascript if else语句不适用于JSON

[英]Javascript If else statement not working with JSON

I have the following code. 我有以下代码。 So basically the JavaScript needs to look at the username and password and check it via an API (which works) and returns true or false. 因此,基本上,JavaScript需要查看用户名和密码,并通过API(有效)进行检查,并返回true或false。 True giving the user access to the next page and false reloading the login page. 设置为true授予用户访问下一页的权限,设置为false则重新加载登录页面的权限。

Everything works perfectly except for the JavaScript if statement. 除了JavaScript if语句外,其他所有东西都可以正常运行。
My code is as follows: 我的代码如下:

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>  

Your code looks fine, except for the type of the success property value. 除了success属性值的类型之外,您的代码看起来还不错。

It could be that the server is not returning a string literal 'true' instead a boolean value true so 服务器可能未返回字符串文字'true'而是返回布尔值true因此

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

When JSON data is true or false. JSON数据为true或false时。 Double quotes cannot be used. 不能使用双引号。

Thank you for the quick responses. 感谢您的快速回复。 Turns out the problem was that the datatypes are clashing, I changed the API response to 1 and 0 and that seemed to have solved the problem. 原来问题是数据类型冲突,我将API响应更改为1和0,这似乎已经解决了问题。 Easier and more flexible when using numbers. 使用数字时更轻松,更灵活。

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