0

私は

        <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  } }

問題は、exist が true の場合にのみ出力されることです。

私が入れたら

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

一方、偽の値も出力します。

4

2 に答える 2

1

この行

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

string と比較して"true"いますが、ブール値がtrue保存されているため、次のように動作するはずです:

if (json.response.exist) {
于 2013-11-08T18:56:26.070 に答える
0

引用符をなくして、恒等演算子 (===) を使用します。期待どおりの結果が得られます

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
}
于 2013-11-08T19:06:13.747 に答える