如何为$ .ajax生成PHP响应

时间:2014-08-13 23:56:34

标签: php jquery ajax

正在使用下面的ajax代码提交表单。我不确定使用PHP生成什么响应,以便$.ajax可以调用相应的回调done()fail()

request = $.ajax({
        url: "php_process.php",
        type: "post",
        data: serializedData
    });

    // callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // log a message to the console
        console.log("Hooray, it worked!");

    });

    // callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // log the error to the console
        console.error(
            "The following error occured: "+
            textStatus, errorThrown
        );
    });`

2 个答案:

答案 0 :(得分:0)

请参阅结果区域的.done().fail()响应,控制台的网络标签

$(function() {
    var urls = ["/echo/jsons/", "/echo/json/"];
    var request = function(url) {

        return $.ajax({
        url: url,
        type: "POST",
        data: {json : JSON.stringify({"abc":[123]}) }            
        });
    };           
    // callback handler that will be called on success
 $.each(urls, function(k, v) {
     $.when(request(v))
    .done(function (response, textStatus, jqXHR){
        // log a message to the console
        console.log("Hooray, it worked!", response);
        $("body").prepend("DONE: <br>" 
                          + Object.keys(response) + ":" 
                          +  response[Object.keys(response)] 
                          + "<br><br>")
    })    
    // callback handler that will be called on failure
   .fail(function (jqXHR, textStatus, errorThrown){
        // log the error to the console
        console.log("The following error occured: "
                    + textStatus, errorThrown);
       $("textarea")
       .before("FAIL: <br>")
       .val(jqXHR.getAllResponseHeaders() +"\n" 
           + jqXHR.status +"\n"+ textStatus 
           +"\n"+ errorThrown +"\n" +  jqXHR.responseText)
    });  
});
});

jsfiddle http://jsfiddle.net/guest271314/L3jbvnex/1/

PHP: How to send HTTP response code?

http://php.net/manual/en/function.http-response-code.php

http://php.net/manual/en/function.header.php

答案 1 :(得分:-1)

只有在从服务器获取响应时出现错误,才会调用

fail()。否则调用done()。所以fail()不依赖于PHP的响应。