繁体   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