簡體   English   中英

如何為$ .ajax生成PHP響應

[英]How to generate a PHP response for $.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
        );
    });`

在控制台的“網絡”選項卡的結果區域中,查看.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:如何發送HTTP響應代碼?

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

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

僅當從服務器獲取響應時出錯時才調用fail() 否則,將調用done() 因此, fail()不依賴於PHP的響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM