12

ajax .done() 関数の使用方法について少し混乱しています。ユーザーがデータベースに存在するかどうかを確認するためにフォームの検証に取り組んでいますが、ajaxが最善のアプローチです(まだ学習中です)。ユーザーが存在する場合はtrue、ユーザーが存在しない場合はfalseを返すphpファイルがあります。done 関数のパラメーターにブール値を渡すにはどうすればよいですか?

$(".check").blur(function(){
  var username = $(".check").val();
  $.ajax({
    url: "validateUser.php",
    type: "post",
    data: "username= " + username
  }).done(function(result){
    if (result == true){
      // User exists
    }else{
      // User doesn't exist
    }
  });
});

それが理にかなっていることを願っています。私はそれを説明するために最善を尽くしました。

4

3 に答える 3

8

結果はデー​​タ文字列なので、 result == 'true' にする必要があると思います

私はちょうどチェックしました、私は正しいです、引用符はそれを機能させます

PHP:

<?php

if($_POST['username']=='sambob'){echo 'true';}else{echo 'false';}

?>

Javascript

username='sambob';

$(".check").blur(function(){
  $.post("validateUser.php", { username: username })
  .done(function(data) {
     if (data == 'true'){
        alert("User exists");
     }else{
        alert("User doesn't exist"); 
     }
  });
});

json PHP

<?php

if($_POST['username']=='sambob'){echo'{"exists":true}';}
                            else{echo'{"exists":false}';}
?>

json Javascript

$(".check").blur(function(){
   $.post("validateUser.php", { username : username },
   function(user){
      if (user.exists == true){
         alert("User exists");
      }else{
         alert("User doesn't exist");
      }
   }, "json");
});
于 2013-04-18T06:38:12.423 に答える
0

成功: XHR の成功ステータスを返します。例: 200
完了: XHR が成功すると、処理が完了し、戻りデータが返されます

。以下のコードを試してください。

 $.ajax({
type: "POST",
url: Url,
data: dataParameter,
async: true,
success: function(results, textStatus) {
    debugger;
    console.log("success : " + results);
},
error: function(xhr, status, error)
{
    console.log("error : " + xhr.responseText);                   
}
}).done(function(results) {
    debugger;          
    console.log("done : " + results);           
});
于 2016-11-23T19:48:34.430 に答える