Phonegap jQuery ajax请求不起作用

我想开发一个Phonegap应用程序,我正在使用jQuery Mobile。 我正在通过PC上的Firefox进行开发和测试,因此这里描述的问题与Phonegap没有任何关系 – 这是一个Firefox PC问题:

以下代码不起作用,我需要一些帮助指出我正确的方向:

var loadWeather = function() { // Request absetzen $.ajax( { // the URL for the request url : 'http://www.google.com/ig/api', // the data to send (will be converted to a query string) data : { weather : 'Vienna' }, // whether this is a POST or GET request type : 'GET', // the type of data we expect back dataType : 'xml', // code to run if the request succeeds; the response is passed to the function success : function(xml) { parseXML(xml); }, // code to run if the request fails; // the raw request and status codes are passed to the function error : function(xhr, status) { alert('Error retreiving weather!'); } }); } 

状态是“错误”,xhr.readyState = 0,xhr.status = 0,所以我根本没有从jQuery获得任何信息。 请求被执行,答案标题(来自Firebug)是:

 Accept: application/xml, text/xml, */*; q=0.01 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Accept-Encoding: gzip, deflate Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 Connection: keep-alive Host: www.google.com Origin: null User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1 

和200 OK。 那么为什么我跳错了? xhr.isRejected()表示正确。 这是什么意思?

好的,所以这里有很多事情要做。 首先,Firefox不允许您使用AJAX执行跨域请求,因此当您从桌面浏览器中尝试使用时,就会出现错误情况。

如果你在设备上进行测试,我会怀疑jQuery会给你一个成功的结果。 您会看到在移动设备上运行来自file://协议的代码时,相同的原始策略不适用。 事实上,我在使用PhoneGap开发的示例应用程序中对该确切的Google API进行了AJAX查询。

但是,根据您使用的jQuery版本,可能存在错误。 通常,当您从file://协议执行AJAX请求时,xhr.status将返回“0”。 这实际上是可以的,应该被视为’200’,但我相信旧版本的jQuery有0状态的问题。

我写了一篇关于从PhoneGap应用程序执行XHR的快速博客文章,您可以阅读:

http://simonmacdonald.blogspot.com/2011/12/on-third-day-of-phonegapping-getting.html

它完全取决于jQuery。 如果这不起作用那么什么都不会。