【问题标题】:succes function doesn't work in $.ajaxsucces 函数在 $.ajax 中不起作用
【发布时间】:2015-03-02 08:38:04
【问题描述】:

我尝试通过 $.ajax 从 API 获取一些数据我设法在我的控制台中获得响应,所以调用没有任何问题,但是 succes 功能不起作用,我什至尝试将警报放入成功功能,但仍然不起作用。

    var symptoms = sessionStorage.getItem('resultSymptoms') ;
    var sendData =  {"patientID":{"ICD9":symptoms,
    "text_type":"long",
    "PatientName":"SomeName",
    "DoctorsName":"SomeName"}}

         $.ajax({
    type: "POST",
    url:  "http://130.211.170.206:8080/freemium",
    contentType :"application/json",
    headers: {          
         Accept : "text/html"         
    }  ,
    dataType: "json",
    data: JSON.stringify(sendData),
      success: function(data) {
        console.log('This is the data '+data.text()) ;
          $('#resultTemplate').html(data.text()) ;
                },
      failure: function(data) {
         console.log(' failed to connect');
      }

});
});

编辑:
当我放一个错误回调函数时,我得到了解析错误

编辑 2:当我将数据类型更改为“文本”时,一切都已修复

【问题讨论】:

  • 它没有调用成功,因为它抛出了一个错误。您编写成功回调的方式,为错误回调编写一个函数并验证错误。您正在请求跨域,可能需要启用CORS。
  • 在尝试之前阅读文档是一个好习惯:api.jquery.com/jquery.ajax
  • 当我放一个错误回调函数时,我得到了解析错误
  • 它不是.failure(),根据文档只有一个.fail() - 捕获错误的方法
  • @ziz194:这可能意味着响应不是 JSON,而是一条错误消息。检查浏览器工具中的网络流量 (F12) 以查看响应是什么。

标签: jquery ajax


【解决方案1】:

试试这个:

$.ajax({
    type: "POST",
    url:  "http://130.211.170.206:8080/freemium",
    contentType :"application/json",
    headers: {          
         Accept : "text/html"         
    }  ,
    dataType: "json",
    data: JSON.stringify(sendData)
})
      .done(function(data) {
          console.log('This is the data '+data.text()) ;
          $('#resultTemplate').html(data.text());
      })
      .error(function(data) {
         console.log(' failed to connect');
      });

【讨论】:

  • success 方法已弃用。请改用done 方法。
  • 为什么你认为使用 promise 中的方法比使用 ajax 设置中的属性效果更好?
  • @Guffa,这总是对我有用,所以我把它贴在这里:)
  • 我不确定是否有方法.failure(),我认为是.fail() 而不是[.fail()](api.jquery.com/deferred.fail/)跨度>
  • 仍然不起作用它说意外令牌'。'在故障线函数中
【解决方案2】:

使用error 属性指定错误处理程序,这将允许您查看错误消息:

var symptoms = sessionStorage.getItem('resultSymptoms');
var sendData = {
  "patientID": {
    "ICD9":symptoms,
    "text_type":"long",
    "PatientName":"SomeName",
    "DoctorsName":"SomeName"
  }
};

$.ajax({
  type: "POST",
  url: "http://130.211.170.206:8080/freemium",
  contentType :"application/json",
  headers: {          
    Accept : "text/html"         
  },
  dataType: "json",
  data: JSON.stringify(sendData),
  success: function(data) {
    console.log('This is the data ' + data.text());
    $('#resultTemplate').html(data.text());
  },
  error: function(xhr, stat, err) {
    console.log('Error: ' + stat + ' ' + err);
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-29
    • 2016-08-05
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2023-03-27
    相关资源
    最近更新 更多