对于ajax响应,哪种方式更好,死亡或回声?

Mad*_*gle 0 javascript php ajax jquery json

我在我的一个网页中使用AJAX.我在这里指定了dataType为JSON.

jQuery.ajax({
    url:  "www.mydomain.com/ajax.php",
    type: "post",
    dataType: "json",
    data:{to_email_address:"myemail@gmail.com"},
    success:function(response){
        response = jQuery.parseJSON(response);
        if(response){
            alert("success");
        }
        else{
            alert("Failed, Try again");
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

ajax.php,我使用echo json_encode如下功能

<?php
    if(!($mail_to_address, $mail_subject, $content, $headers)) {
        echo json_encode(false);
    }
    else{
        echo json_encode(true);
    }
?>
Run Code Online (Sandbox Code Playgroud)

但我已经在某个地方看到了,dieecho不仅仅是喜欢

<?php
    if(!($mail_to_address, $mail_subject, $content, $headers)) {
        die(json_encode(false));
    }
    else{
        die(json_encode(true));
    }
?>
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释哪种方式更好,为什么?提前致谢 ..

Han*_*nky 5

如果你echo不这样做die,那你就冒着错误地在某一天产生更多输出而不是需要的风险.

如果你die,它打印并结束那里的一切.这是唯一的区别.

以下是使用代码的示例

<?php
    if(!($mail_to_address, $mail_subject, $content, $headers)) {
        echo json_encode(false);    // a die would stop everything here
    }
    else{
        echo json_encode(true);
    }
    echo "oops this was mistakenly printed";  // this breaks your JSON
?>
Run Code Online (Sandbox Code Playgroud)

如果你使用die而不是echo那么最后一个echo不会破坏你,JSON因为它永远不会执行.

如果您知道在有条件检查后没有任何内容,或者您​​确信没有特殊原因可以使用die(),您可以继续使用您的echo.因此,您的问题的答案是:只要您的输出在您的控制之下,它们都不会优于另一个.