PhoneGap ajax调用每次失败
我使用 PhoneGap 开发移动应用程序,我必须访问来自其他项目的一些服务。
我使用 jquery-2.0.0.js 和 jquery-mobile-1.3.2.js 。
I am developing a mobile application using PhoneGap, and I have to access some services from another project. I am using jquery-2.0.0.js and jquery-mobile-1.3.2.js.
$.ajax({
url: 'http://localhost:62465/api/account?email=johndoe@yahoo.com',
dataType: 'json',
success: function (data) {
alert(data.Name);
},
error: function (xhr, type) {
alert("Failed to load data");
alert(xhr + " " + type);
}
});
此ajax调用每次都失败。在 config.xml 中,我有以下行:< access origin =*/>
This ajax call fails everytime. In the config.xml I have the following line: <access origin="*" />
我可能会错了!
问题是你的phonegap应用程序请求一个本地文件来自不是Web服务器的东西。本地文件传递与没有HTTP HEADERS - 这意味着没有200 OK标题和没有404未找到错误。因此,状态代码假定为0。
The problem is that your phonegap application is requesting a local file from something that isn't a webserver. The local file is delivered with NO HTTP HEADERS - that means no "200 OK" header and no "404 Not Found" errors. So, the status code is assumed to be 0.
直接javascript XHR将需要忽略状态,并对readystate == 4(完成并准备好)执行您的操作。像这样:
Straight javascript XHR will need to ignore status and perform your action on readystate == 4 (finished and ready). Like this:
var myrequest = new XMLHttpRequest();
myrequest.open('GET','localfile.html');
myrequest.onreadystatechange = function(){
if(myrequest.readyState == 4) {
var result = myrequest.responseText;
}
}
myrequest.send();
在MooTools中,在Request类中实现改变的状态测试是一个相对简单的任务 - 返回代码测试也接受0为真。像这样:
In MooTools, it's a relatively straightforward task of implementing an altered status test in the Request class - altering the return code test to also accept 0 for true. Like this:
Request.implement({
isSuccess: function(){
var status = this.status;
return ((status >= 200 && status < 300) || status === 0);
}
});
jQuery ....我有一些事情我想谈谈jQuery - 因为这似乎是一个优雅的地方。
jQuery.... I have some things I'd like to say about jQuery - but I'll hold my tongue because this seems like a classy place.
要准备jQuery的状态== 0,你需要使用always事件而不是成功事件,你
To prepare jQuery for status == 0, you need to use the always event instead of the success event, you can test the status code there.
$.ajax({
url: '/echo/html/',
type: 'PUT',
data: "email=a@b.com"
}).always(function(data, textStatus, jqXHR){
switch(textStatus) {
case 200:
case 0:
alert('Success.');
break;
case 404:
alert('oops');
break;
}
});
Ajax in Cordova / Phonegap - Yay!
Ajax in Cordova/Phonegap - Yay!