【问题标题】:How to call an exception with post method (AJAX)?如何使用 post 方法(AJAX)调用异常?
【发布时间】:2015-05-19 03:47:00
【问题描述】:

如果 post 方法不成功,我想抛出异常并写入错误日志?基本上,如果这个方法没有返回任何结果,我想抛出一个异常并写入文件。

发布方式:

$.post("ip.php", function( data ){
$("#ip").val(data.ip);
$("#country").val(data.country);
$('#campaignID').val(data.campaignID);
}, "json");

【问题讨论】:

    标签: javascript jquery ajax exception post


    【解决方案1】:

    对于问题的一部分:

    如果 post 方法不成功我想抛出一个异常 (...)

    您可以将.fail() callback 方法链接到$.post() 请求,如@Grimbode 所述

    或者使用$.ajax() 代替,error 选项在哪里 - 如果请求失败则调用函数。
    $.ajax() 等效于您的 $.post() 方法将是:

    $.ajax({
        type     : "POST",
        url      : "ip.php",
        dataType : 'json',
        success  : function(data){
            $("#ip").val(data.ip);
            $("#country").val(data.country);
            $('#campaignID').val(data.campaignID);
        },
        error   : function(jqXHR/*object*/, textStatus/*string*/, errorThrown/*object*/){
            // throw an error ...
            // console.log('Type of error: ' + textStatus);
        },
    });
    

    至于那部分:

    (...) 写入错误日志

    不可能用 javascript 编写任何文件。由于它是在客户端浏览器中执行的client side scripting language,因此它无法访问服务器。嗯,就是这样。

    【讨论】:

    • 谢谢,你的回答很完整!
    【解决方案2】:

    只需添加 fail(); 方法。

    var jqxhr = $.post( "example.php", function() {
      alert( "success" );
    })
    .done(function() {
      alert( "second success" );
    })
    .fail(function() {
      alert( "error" );
    })
    .always(function() {
      alert( "finished" );
    });
    

    【讨论】:

      猜你喜欢
      • 2012-12-02
      • 2016-11-24
      • 2018-11-18
      • 2023-03-25
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多