2017-10-16 17 views
0

私はチェックアウトが成立したときにtrueまたはfalseを返すサーバサイドコードをいくつか持っています。コンソールログを通じて、これは{"success": true, "message": "Added to db"}のようになります。回答が真であれば、私たちは何かをする、そうでなければ何かをするという、Ajaxの成功条件を正しく書く方法はありますか?サーバajaxからの回答

ハンドラPHP

 echo json_encode(['success' => true, 'message' => 'Added to db']); 
    } 
} else { 
    echo json_encode(['success' => false, 'message' => 'Wrong captcha']); 
} 

のindex.php

$(document).ready(function() { 
    $('#submit').click(function() { 
     var username = $('#username').val(); 
     var email = $('#email').val(); 
     var message = $('#message').val(); 
     var captcha = $('#captcha').val(); 

     if(username === ''){ 
      alert('Please input data in all fields'); 
     } else { 
      $.ajax({ 
       type: "POST", 
       cache: false,   
       url: '/data/insert.php', 
       data: {username: username, email: email, message: message, captcha: captcha}, 
       success: function(response) { 
        console.log(response); 
       } 
      }); 
     } 
    }); 
}); 

答えて

0

は、Ajaxは、エラーが発生したかどうかを判断するためにHTTPヘッダを見ていきます。

if ($someCondition) { // If the request is good 
    echo json_encode(['message' => 'Added to db']); 
} else { // Request is bad. You can add any number of conditions and return any number of errors 
    header('HTTP/1.1 400 Bad Request'); 
    exit(json_encode(['message' => 'Some error message', 'code' => 400])); 
} 

あなたは、クライアント・エラーhere

その後、あなたのAjaxのための特定のエラーハンドラ関数がありますの一覧を見ることができます:あなたは、応答を検証しているときに、サーバー上のエラーコードを設定することができます

$.ajax({ 
     type: "POST", 
     cache: false,   
     url: '/data/insert.php', 
     data: {username: username, email: email, message: message, captcha: captcha}, 
     success: function(response) { 
      console.log(response.message); 
     }, 
     error: function(response) { 
      alert(response.message); 
     } 
}); 
0
$(document).ready(function() { 
     $('#submit').click(function() { 
      var username = $('#username').val(); 
      var email = $('#email').val(); 
      var message = $('#message').val(); 
      var captcha = $('#captcha').val(); 
      if(username === ''){ 
       alert('Please input data in all fields'); 
      } 
      else { 
      $.ajax({ 
       type: "POST", 
       cache: false,   
       url: '/data/insert.php', 
       data: {username: username, email: email, message: message, captcha: captcha}, 
       success: function(response) { 
       if(response.success == true){ 
        // do some thing 
       }else{ 
        // do some thing 
       } 
       } 
      }); 
     } 
     }); 
    }); 
+0

条件はまだ他に –

+0

成功です:機能(応答){ 場合(response.success ==真){ console.log( 'true'); } else { console.log( 'false') } } –

+1

コードのみの回答は、正しい結果を得るための鍵を指摘しないことが多いため、推奨されません。あなたはこの答えについてもっと記述できるものはありますか? – lit

関連する問題