简体   繁体   English

如何为$ .ajax生成PHP响应

[英]How to generate a PHP response for $.ajax

A form is being submitted using the ajax code below. 正在使用以下ajax代码提交表单。 I am unsure what response to generate using PHP, so that $.ajax can call the appropriate callbacks done() and fail() 我不确定使用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
        );
    });`

See .done() and .fail() responses at result area , network tab at console 在控制台的“网络”选项卡的结果区域中,查看.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/ jsfiddle http://jsfiddle.net/guest271314/L3jbvnex/1/

See 看到

PHP: How to send HTTP response code? PHP:如何发送HTTP响应代码?

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

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

fail() is only called if there is an error in getting the response from server. 仅当从服务器获取响应时出错时才调用fail() Else the done() is called. 否则,将调用done() So fail() doesn't depend on the response from the PHP. 因此, fail()不依赖于PHP的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM