Ajax请求失败,看不清楚原因

时间:2012-12-15 13:17:23

标签: jquery ajax api get request

我已经创建了一个在json中返回数据的API,现在我正在创建一个应用程序,通过接收数据并在页面上使用它来测试API。但是,我的ajax代码(见下文)因某种原因失败,错误只是“错误”(错误:错误)。

代码有什么问题?

代码:

    $.ajaxSetup ({
      url: "http://localhost:8000/products", // <--- returns json
      type: "GET",
      headers:{
        "Accept":"application/json",
        "Content-type":"application/x-www-form-urlencoded"
      }
    })
    $.ajax({
        success: function(data){
            console.log("You made it!");
        },
        error: function(xhr) {
           console.log("Error: " + xhr.statusText);
       }
    }).done(function(data){
        console.log(data);
    })

这是我在Chrome(Inspector - &gt;网络)中获得的信息:

名称产品localhost /,方法:获取,状态:(已取消),类型:待定,发起人: jquery-latest.js:8434脚本,大小: 13B 0B,时间: 95ms 0.0天

5 个答案:

答案 0 :(得分:9)

可能是什么问题

我想我知道你的问题。看起来你正在加载一个协议+域+端口(例如“http://localhost/”)的页面,但随后调用AJAX请求到不同的协议,域或端口(在这种情况下,可能只有端口不同:“{{ 1}})。

这样您可能会遇到Same Origin Policy限制,这是您浏览器的安全功能。在这种情况下,浏览器可能会指示特定请求已被“取消”(因为浏览器阻止了它)。

解决方案

您的问题有多种解决方案:

  • (最简单)坚持原始站点和AJAX请求的端点的相同协议+域+端口,
  • (第二个最简单)在服务器上构建一个终点,例如。 “http://localhost:8000/products"”会在后台调用“http://localhost/products”,并会返回其响应(作为SOP的解决方法),
  • 一些更复杂的解决方案,如JSONP,CORS等(更多这里:https://stackoverflow.com/a/8467697/548696),

答案 1 :(得分:5)

$.ajax({
    /* ajax options omitted */
    error: function (xmlHttpRequest, textStatus, errorThrown) {
         if(xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0) 
              return;  // it's not really an error
         else
              // Do normal error handling
});

答案 2 :(得分:2)

尝试使用

$.ajax({
  url: "http://localhost:8000/products", 
  dataType: 'json',
  success: function(data){
            console.log("You made it!");
        },
        error: function(xhr) {
           console.log("Error: " + xhr.statusText);
       }
});

您可以在成功中使用代码行或完成回调,而不是使用完成回调。它非常简单和清洁。

答案 3 :(得分:0)

为什么不尝试将两个ajax调用合并为一个。并尝试更改type = "POST"

$.ajax({
    type: "POST",
    url: "http://localhost:8000/products",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    error: function(errMsg) {
        alert(errMsg);
    }
});

答案 4 :(得分:0)

我认为您的浏览器缓存了错误,或者可能是正确设置标头时出现问题,因此请尝试在$.ajaxsetup()中添加此方式:

    $.ajaxSetup ({
      url: "http://localhost:8000/products", // <--- returns json
      type: "GET",
      dataType: 'json',
      cache: false,
      contentType: "application/json"
    });

尝试这种方式,看看是否有效。