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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看