【问题标题】:AJAX - the request is done correctly but the error function is executedAJAX - 请求正确完成但错误函数被执行
【发布时间】:2018-05-23 20:50:38
【问题描述】:

我有一个来自服务器的 AJAX 请求,将一个用户保存在数据库中:

JavaScript

u.first_name = "chaabaoui";
u.last_name = "aymene";
u.mot_de_passe = "123";
u.type = 0;
u.email = "ekka@gmail.com";         
$.ajax({
    url : "http://localhost:8080/utilisateurs/addUser",
    headers: { 
        'Accept': 'application/json',
        'Content-Type': 'application/json' 
    },
    type : "POST",
    data : JSON.stringify(u),
    dataType : "application/json",
    success : function(response) {
                  console.log("the request is done,");
                  if(response == "true") {
                      console.log("and the user was saved");
                  } else {
                      console.log("but the user was not saved");
                  }
              },
    error : function(error) {
                console.log("the request was failed ", error);
            },
    complete : function(xhr , status) {
                   console.log("the requeste is complete");
               }
});

问题用户已保存到数据库,但显示来自错误函数的错误消息(“请求失败”)而不是成功消息。我需要知道这里出了什么问题。最重要的是,为什么没有执行成功消息?

提前谢谢你。

【问题讨论】:

  • 响应如何,返回什么状态码?
  • 检查 devtools 中的 Network 选项卡以查看对请求的响应。
  • dataType : "application/json", 无效。如果服务器返回JSON,应该是dataType: "json"
  • 标题中不需要'Accept': 'application/json',,使用dataType: "json"时会自动完成。
  • 谢谢@NielsNet,状态码是200

标签: jquery ajax http


【解决方案1】:

看到你的控制台应该足以看到错误,因为你有:

 error : function(error){
             console.log("the request was failed ", error);
         },

但如果它没有显示任何内容,只需使用 chrome(或其他浏览器)在网络选项卡(开发人员工具)上检查您的请求,它应该至少是错误请求并带有响应消息

https://developers.google.com/web/tools/chrome-devtools/network-performance/reference

【讨论】:

    猜你喜欢
    • 2011-01-30
    • 1970-01-01
    • 2016-09-08
    • 2011-08-12
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多