2

我创建了一个以 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 -> Network) 中获得的信息:

名称: products localhost/,方法: GET,状态:(已取消),类型: Pending,发起者: jquery-latest.js:8434 脚本,大小: 13B 0B,时间: 95ms 0.0天

4

5 回答 5

10

可能是什么问题

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

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

解决方案

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

  • (最简单)为原始站点和 AJAX 请求的端点坚持相同的协议+域+端口,
  • (第二个最简单的)在服务器上建立一个端点,例如。" http://localhost/products" 将在后台调用 " http://localhost:8000/products" 并返回其响应(作为 SOP 的预演),
  • 一些更复杂的解决方案,如 JSONP、CORS 等(更多信息:https ://stackoverflow.com/a/8467697/548696 ),
于 2012-12-15T17:51:27.867 回答
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
});
于 2012-12-15T13:23:44.793 回答
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);
       }
});

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

于 2012-12-15T13:32:55.223 回答
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);
    }
});
于 2012-12-15T13:23:04.073 回答
0

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

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

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

于 2012-12-15T13:55:48.923 回答