【发布时间】: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