侦听 ajax 操作的响应


Listen for response of ajax action

我有一个函数,我可以将数据提交到另一个 php 页面,该页面将其输入数据库。

$(document).on('click', '.addNumber', function() {
    var newNum = $('input#newNumber').val();
        $.ajax({
            type: 'POST',
            url:  '/addNewPhoneNumber.ajax',
            data: {
                'bid' : bid,
                'nbr' : newNum
            },
            dataType : 'json'
        });
});

我需要扩展功能并在我的另一个 php 页面上添加对提交号码的检查。如果它已经在我的数据库中,我需要返回一些标志并在第一页上显示一条消息。我知道如何在第二页上执行此操作,但是如何将响应返回到初始页面?

添加这样的成功回调

$.ajax({
        type: 'POST',
        url:  '/addNewPhoneNumber.ajax',
        data: {
            'bid' : bid,
            'nbr' : newNum
        },
        dataType : 'json',
        success: function (response) {
        if(response.status === "success") {
            // do something with response.message or whatever other data on success
        } else if(response.status === "error") {
            // do something with response.message or whatever other data on error
        }
    }
    });

你可以成功和错误回调函数

$.ajax({
    type: 'POST',
    url:  '/addNewPhoneNumber.ajax',
    data: {
        'bid' : bid,
        'nbr' : newNum
    },
    dataType : 'json',
    success: function(response, status, x) {
        console.log(response) //response is the output of your page.. you can write it somewhere
    },
    error: function(h, s, x) {
        console.log("error: " + h.statusText)
    }
  }
});