2

I'm working on a BlackBerry application using phonegap. The problem is, it doesn't get an external JSON from my server on a real device, altough it works well on Ripple.

First, I've added <access subdomains="true" uri="*" /> to the build.xml file.

This is my html/javascript code:

<script>
function onLoad() {
   $.ajax({
      type : 'GET',
      url : "http://myserver.com/api/test.php",
      jsonpCallback : 'jsonCallback',
      crossDomain : true,
      cache : false,
      dataType : "jsonp",
      jsonp: 'callback',
      success: function(json) {
         $( ".info" ).html("success");
      },
      error: function(xhr, textStatus, errorThrown) {
         $( ".info" ).html("Error: " + textStatus + ":" + errorThrown);
      }
});
}
</script>
<body onload="onLoad();">
...
</body>

When I run this on the Ripple emulator, the success callback is called, but on a real device (BlackBerry 7.0) I get this output:

parsererror: json callback was not called.

As a side note, I have validated the response in JSONLint and it's ok. Also, the response is a valid jsonp response:

jsonCallback({"result":{"status":"ok","testText":"There goes my content"}});

Furthermore, I put code on my server to log access, and it's not being called, so I guess the problem is not my server code, but on the mobile code somewhere.

4

3 回答 3

1

您不需要使用 jsonp 调用,而是最好进行普通的 json 调用。在您的服务器端抛出一些像这样的 php 标头:

  <?php
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
  header('Access-Control-Max-Age: 1000');
  header('Access-Control-Allow-Headers: Content-Type');
  ?>

您将能够使用所有 jQuery AJAX 回调。

于 2013-06-05T17:30:00.293 回答
0

我有同样的问题......我通过将预期的 contentType 设置为我的 ajax 调用来解决它。

内容类型:“应用程序/json;字符集=utf-8”

skrip最终看起来像这样。

$.ajax({
  type: "GET",
  url: "http://myUrl.com/jsonFile.json.js",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data) { // Response function
    //work with your data
  },
  error : function () {
     //Handle your errors
  }
});

我请求的文件只是一个带有 json 内容的 js 文件,例如: [{"id":"1","name":"lol"}...]

希望这可以帮助某人:)

于 2013-11-07T08:24:44.743 回答
0

你试过不使用jsonp吗?

 $.ajax({
      type : 'GET',
      url : "http://myserver.com/api/test.php",
      dataType : "text",
      success: function(jsonText) {
         var json = $.parseJSON(jsonText);
         $( ".info" ).html("success");
      },
      error: function(xhr, textStatus, errorThrown) {
         $( ".info" ).html("Error: " + textStatus + ":" + errorThrown);
      }

以防万一,在尝试之前确保您的设备可以访问互联网!

编辑

您是否尝试过@GEMI 评论中的解释?

要从您的网站访问外部网站,您需要将域名添加到应用的白名单中。这是在 config.xml 文件中完成的:

<access subdomains="true" uri="http://my.domain.com" /> 

此外,如果您使用的是 PhoneGap API 或 BlackBerry WebWorks API,则需要在域下添加适当的功能:

<feature id="phonegap" required="true" version="0.9.3" /> 
于 2013-06-05T22:40:29.303 回答