??yy 2017-10-16 15:42 采纳率: 0%
浏览 15

来自服务器ajax的答复

I have some server side code that, upon the checkout being fulfilled returns either a true or a false. Through the console log it looks like this {"success": true, "message": "Added to db"}. How can I correctly write in the ajax success condition that if the answer is true, then we do something, otherwise we do something else?

handler 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);
                }
            });
        }
    });
});
  • 写回答

2条回答 默认 最新

  • weixin_33695082 2017-10-16 15:55
    关注

    Ajax will look at the http headers to determine if there was an error. You can set the error codes on your server when you're validating the response:

    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]));
    }
    

    You can see a list of client errors here

    Then for your ajax there's a specific error handler function:

    $.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);
            }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效