【问题标题】:jQuery.ajax fail handler not called未调用 jQuery.ajax 失败处理程序
【发布时间】:2020-10-15 07:37:28
【问题描述】:

根据jQuery documentation

弃用通知: jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调从 jQuery 3.0 开始被删除。您可以改用 jqXHR.done()、jqXHR.fail() 和 jqXHR.always()。

但是当我使用以下代码时:

$.ajax({
    type: 'GET',
    url: '@Url.Page("Create", "History")',
    contentType: 'application/json',
    dataType: 'json',
    data: { 'name': value },
    done: function (response) {
        alert('done' + response);
    },
    fail: function (response) {
        alert('fail' + response);
    },
    error: function (response) {
        alert('error' + response);
    },
    success: function (response) {
        alert('success' + response);
    },
});

如果我的 Razor Pages 处理程序引发异常,则会显示 错误 响应。 (如果我删除 error 处理程序,则不会显示任何内容。)

如果喜欢的话,我不介意使用fail。但如果它不会在错误时被调用,它不会有太大的好处。

UPDATE:我还可以看到 done 处理程序也不会被调用,除非我将其更改为 success

更新:看起来我使用的是 jQuery 3.3.1。

【问题讨论】:

  • 只需使用$.ajax(...).then(() => { /* all good */}).catch(() => { /* error */ }),因为它们都可以正常工作...
  • @balexandre:我尝试只使用then: function ()...catch: function(),但它们都没有被调用。功能上不是和你一样吗?
  • 在 jQuery 页面上做一些测试,只是复制/粘贴他们的例子

标签: javascript jquery asp.net asp.net-core razor-pages


【解决方案1】:

就用jQuery documentation,好久没用jQuery了,尽量避免,现在有好多更好的工具?

jqXHR = $.ajax({
    type: 'GET',
    url: '/',
    contentType: 'application/json',
    dataType: 'json',
    data: { 'name': 123 }
}).promise();

jqXHR.done(function( data, textStatus, jqXHR2 ) { console.log('TEST 1: done', textStatus) });
jqXHR.fail(function( jqXHR2, textStatus, errorThrown ) { console.log('TEST 1: fail', textStatus) });
jqXHR.always(function( data, textStatus, errorThrown ) { console.log('TEST 1: always', textStatus) });
jqXHR.then(
  function( data, textStatus, jqXHR2 ) { console.log('TEST 1: then1', textStatus) }, 
  function( jqXHR2, textStatus, errorThrown ) { console.log('TEST 1: then2', textStatus) }
);

// or you can write


$.ajax({
  type: 'GET',
  url: '/',
  contentType: 'application/json',
  dataType: 'json',
  data: { 'name': 123 }
})
.done(function(data, textStatus) {
  console.log( "TEST 2: success", textStatus );
})
.fail(function(data, textStatus) {
  console.log( "TEST 2: error", textStatus );
})
.always(function(data, textStatus) {
  console.log( "TEST 2: complete", textStatus );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

【讨论】:

  • 这基本上是我最终做的。我不知道done: function () { }.done(function () {}) 之间有什么区别,但由于某种奇怪的原因,前者似乎不可靠。
  • 只要它有效......这就是重要的部分?
猜你喜欢
  • 1970-01-01
  • 2011-07-15
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多