如何用post方法调用异常(AJAX)?

How to call an exception with post method (AJAX)?

如果post方法不成功我想抛出异常并写入错误日志?基本上,如果此方法 returns 没有结果,我想抛出异常并写入文件。

Post方法:

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

只需添加 fail(); 方法。

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

对于问题的部分:

If the post method is unsuccessful I want to throw an exception (...)

你可以链接一个 .fail() callback method to the $.post() request as mentioned by

或者改用 $.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);
    },
});

至于那部分:

(...) write to an error log

无法使用 javascript 写入任何文件。由于它是在客户端浏览器中执行的 client side scripting language,因此它无法访问服务器。好吧,这就是它的工作原理。