Javascript输出表现得很奇怪

Javascript output is acting wierd

本文关键字:输出 Javascript      更新时间:2023-09-26

我有一个

        <p id="err_output"></p>

在我的页面上,它链接到这个JavaScript:

$(document).ready(function($) {
    $("#username").on('keyup',check_username_existence);
 });

函数是这样的:

function check_username_existence(){
    $.ajax({ url: './php/user_name_availability.php',
         data: { username : $('#username').val() },
         type: 'post',
         success: function(output) {
                var json = $.parseJSON(output);
                $('#err_output').html(json.response.exist);
                if(json.response.exist == 'true'){
                //  $('#err_output').html('Exists');
                }
         }
    });
};

JSON 响应的值为:

{ "response" : { "exist" : true   } }
{ "response" : { "exist" : false  } }

问题是它只在存在为真时才输出。

如果我把

 $('#err_output').html( output + json.response.exist);

另一方面,它也会输出错误值。

此行

if(json.response.exist == 'true'){

与字符串"true"进行比较,但您存储了一个布尔true,它应该适用于:

if (json.response.exist) {

去掉引号并使用标识运算符 (===)。它会给你你期望的结果

if(json.response.exist === true){

弱比较会给你奇怪的结果。下面是一个示例,说明它为什么要评估代码中的方式。

bool = "false";
if(bool){
  // bool evaluates to true because it is defined as a string
}
bool = 'true';
if(bool == true){
  // doesn't execute. comparing string to boolean yields false
}