【问题标题】:PhoneGap, jQuery getJSON and CORSPhoneGap、jQuery getJSON 和 CORS
【发布时间】:2013-06-14 03:48:08
【问题描述】:

我正在开发基于 PhoneGap 的移动应用程序。我需要使用 AJAX,我正在使用 jQuery。

我正在尝试使用 CORS 从 PHP 上的 WS 获取 JSON,但出现错误,并且错误消息为空。我在 Web 浏览器中测试了代码,它可以工作。但是,当我将它与 PhoneGap 一起使用时,它不起作用。我用 Fecebook WS 在 PhoneGAp 中测试了我的代码,它可以工作。这是我测试的组合:

测试 1
来源:file:///C:/.../index.html(网络浏览器)
网络服务:http://localhost/.../getemployees.php
结果:有效

测试 2
来源:PhoneGap
网络服务:http://localhost/.../getemployees.php
结果:它不起作用

测试 3
来源:PhoneGap
网络服务:https://graph.facebook.com/OldemarshCr
结果:有效

这是代码:

$.getJSON(url, function (data) {console.log(data);})
.success(function() { console.log("second success"); })
.error(function(jqXHR, textStatus, errorThrown) {
console.log('******* '+"error: " + textStatus+' *******');
});

这是 JSON 响应:

{"items":[{"id":"10","firstName":"Kathleen","lastName":"Byrne","title":"Sales Representative","picture":"kathleen_byrne.jpg","reportCount":"0"},{"id":"9","firstName":"Gary","lastName":"Donovan","title":"Marketing","picture":"gary_donovan.jpg","reportCount":"0"},{"id":"7","firstName":"Paula","lastName":"Gates","title":"Software Architect","picture":"paula_gates.jpg","reportCount":"0"]}

谢谢,

【问题讨论】:

  • 你用安卓模拟器吗?

标签: android jquery ajax cordova cors


【解决方案1】:

在ajax调用中,尝试添加

         $.ajax({
                crossDomain: true,                 
                xhrFields: {withCredentials: true}
              });

【讨论】:

  • 我没有使用ajax方法,但我会尝试使用它
【解决方案2】:

$.ajax 不起作用...这是我得到的错误

{"readyState":0,"responseText":"","status":0,"statusText":"error"}

我在网络浏览器上测试了代码,它工作正常。

这是代码:

$.ajax({
  crossDomain: true,  
  xhrFields: {withCredentials: true},
  type: 'GET', 
  url: url, 
  dataType: 'json', 
  success: function(response){ console.log(response); }
  error: function(error){ console.log('Error: '+error); }
});

谢谢,

【讨论】:

    【解决方案3】:

    好消息!!

    我解决了这个问题。 getJSON 和 ajax 这两种方法都有效,问题出在服务器上。

    当我从外部服务器(不是本地主机)访问 Web 服务时,它可以工作。

    谢谢,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 2014-01-20
      • 2014-05-12
      相关资源
      最近更新 更多