【问题标题】:Issue with AJAX requests with in browser浏览器中的 AJAX 请求问题
【发布时间】:2012-05-10 00:22:54
【问题描述】:

我正在对我的服务器执行一些 AJAX 请求。两种情况的请求类型和参数完全相同,但来自服务器的响应类型不同。

案例 1

这是 Titanium 中使用钛网络 http 客户端的实现。

var xhr = Ti.Network.createHTTPClient({
    onload : function() {
        alert('sucess');
    },
    onerror : function(e) {
         alert('error');
    },
    timeout : 5000
});
var main_url = "http://localhost:3000/shops/560/login.json?api_token=some_token&customer[phone_number]=9988776655&customer[pin]=9876";
xhr.open('GET', main_url);
xhr.send();

完美地返回响应,似乎对我有用。

案例 2

这是使用 JQuery AJAX 方法在本地文件中的实现。

var main_url = "http://localhost:3000/shops/560/login.json?api_token=some_token&customer[phone_number]=9988776655&customer[pin]=9876";

       $.ajax({
        url: main_url,
        type: "GET",
        dataType: "json",
        timeout: 5000,
        success: function(data, status, xmlstatus) {
            alert("success");
        },
        error: function(data, status, xmlstatus){
            if (t === "timeout") {
                alert("timeout");
            } else {
                alert("some error");
            }
        }
     });

但由于浏览器中的跨域政策,它会返回

 XMLHttpRequest cannot load http://localhost:3000/shops/560/login.json?api_token=some_token&customer[phone_number]=9988776655&customer[pin]=9876. Origin null is not allowed by Access-Control-Allow-Origin.

所以,为了避免这种情况,我添加了另一个参数

 &callback = ?

但它仍然返回

 alert('some error');

无法弄清楚问题出在哪里。 当 URL、参数、类型都一样。

----------------编辑---------------

挖掘iniside给了我回应:

 console.log(data) => parsererror

 console.log(xmlstatus) => jQuery164023596301255747676_1335786441349 was not called

【问题讨论】:

  • 尝试使 url 相对:url: "/shops/560/login.json?api_token=some_token&customer[phone_number]=9988776655&customer[pin]=9876"。我已经看到 jQuery 认为由于指定了端口而正在查询外部服务器的实例。
  • dataType: "json", 应该是 dataType: "jsonp",
  • @AnthonyGrist 抱歉,这不起作用。
  • @RoryMcCrossan 我无法将 URL 设为相对。我需要添加服务器的地址,因为我是从本地文件发出请求,而不是来自服务器的一些 html。我正在尝试发出跨域请求。
  • “一些错误”?您没有更好的错误信息吗?

标签: jquery error-handling cross-browser jsonp


【解决方案1】:

当您谈到“本地文件”时,请注意,如果您使用协议 file:// 加载文件,则不能在 ajax 中做很多事情。即使服务器是 localhost,也需要使用 http://。

【讨论】:

  • @即使在本地主机上运行后,结果似乎不受影响,错误与上面更新的相同
  • 好的。我看到了你的错误信息。所以问题与使用的协议无关。
  • 它的解决方法是什么?我阅读了许多博客和方法,但没有一个有效。
  • 我不明白你的评论。你在寻找关于 jsonp 的解释吗?
【解决方案2】:

我认为您的服务器不是用 jsonp 回答,而是用 json 回答。

JSONP 答案是这样的:

callback(someJson)

其中 callback 是您提供的回调名称或 jquery 自动提供的名称。您不能简单地在 JSONP 中调用为 JSON 查询而创建的服务器。

这是一个示例(有点复杂,它是真实的代码,但也许您会过滤与您的问题无关的内容):

客户:https://github.com/Canop/braldop/blob/master/chrome/braldop/inext_com.js

服务器:https://github.com/Canop/braldop/blob/master/go/src/braldopserver/BraldopServer.go

【讨论】:

  • 这是服务器端的错误 wand 没有回复我的回调:)
猜你喜欢
  • 2016-03-14
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
  • 2012-01-30
相关资源
最近更新 更多