如何使用json的phonegap来纠正这个程序

时间:2012-01-12 09:46:59

标签: ajax cordova

我正在使用json的phonegap。我得到了一个错误     索引/ HTML

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />

    <script src="phonegap-1.2.0.js"></script>
    <script src="js/jquery-1.5.min.js"></script>
    <script src="js/load-json.js"></script>

    <script>
        function onBodyLoad() {     
            document.addEventListener("deviceready",onDeviceReady,false);
        }


    </script>

</head>
<body onload="onBodyLoad()">
    <div id="output"></div>
</body>
</html>

Json.js



$(document).ready(function(){
    $(document).bind('deviceready', function(){
        var output = $('#output');

        $.ajax({
            url: 'http:192.168.1.3:8000/index',
            dataType: 'jsonp',
            jsonp: 'jsoncallback',
            timeout: 5000,
            success: function(data, status){
                $.each(data, function(i,item){ 
                    var landmark = '<h1>'+item.name+'</h1>'
                    + '<p>'+item.latitude+'<br>'
                    + item.longitude+'</p>';

                    output.append(landmark);
                });
            },
            error: function(){
               output.text('There was an error loading the data.');
            }
        });
    });
});



 01-12 15:08:52.050: I/System.out(338): loadUrl(file:///android_asset/www/index.html)
    01-12 15:08:52.050: I/System.out(338): url=file:///android_asset/www/index.html baseUrl=file:///android_asset/www
    01-12 15:08:52.230: W/System.err(338): java.net.SocketException: Permission denied
    01-12 15:08:52.230: W/System.err(338):  at org.apache.harmony.luni.platform.OSNetworkSystem.socket(Native Method)
    01-12 15:08:52.230: W/System.err(338):  at dalvik.system.BlockGuard$WrappedNetworkSystem.socket(BlockGuard.java:335)
    01-12 15:08:52.230: W/System.err(338):  at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:216)
    01-12 15:08:52.230: W/System.err(338):  at org.apache.harmony.luni.net.PlainServerSocketImpl.create(PlainServerSocketImpl.java:40)
    01-12 15:08:52.240: W/System.err(338):  at java.net.ServerSocket.<init>(ServerSocket.java:120)
    01-12 15:08:52.240: W/System.err(338):  at java.net.ServerSocket.<init>(ServerSocket.java:74)
    01-12 15:08:52.240: W/System.err(338):  at com.phonegap.CallbackServer.run(CallbackServer.java:177)
    01-12 15:08:52.240: W/System.err(338):  at java.lang.Thread.run(Thread.java:1019)
    01-12 15:08:53.299: D/szipinf(338): Initializing inflate state
    01-12 15:08:53.299: D/szipinf(338): Initializing zlib to inflate
    01-12 15:08:53.349: D/szipinf(338): Initializing inflate state
    01-12 15:08:53.349: D/szipinf(338): Initializing zlib to inflate
    01-12 15:08:54.819: D/PhoneGapLog(338): file:///android_asset/www/index.html: Line 13 : ReferenceError: Can't find variable: onDeviceReady
    01-12 15:08:54.819: E/Web Console(338): ReferenceError: Can't find variable: onDeviceReady at file:///android_asset/www/index.html:13
    01-12 15:09:15.029: D/dalvikvm(338): GC_CONCURRENT freed 361K, 52% free 2806K/5767K, external 884K/1038K, paused 6ms+4ms
    01-12 15:09:45.860: I/System.out(377): loadUrl(file:///android_asset/www/index.html)
    01-12 15:09:45.909: I/System.out(377): url=file:///android_asset/www/index.html baseUrl=file:///android_asset/www
    01-12 15:09:46.299: W/System.err(377): java.net.SocketException: Permission denied
    01-12 15:09:46.299: W/System.err(377):  at org.apache.harmony.luni.platform.OSNetworkSystem.socket(Native Method)
    01-12 15:09:46.299: W/System.err(377):  at dalvik.system.BlockGuard$WrappedNetworkSystem.socket(BlockGuard.java:335)
    01-12 15:09:46.299: W/System.err(377):  at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:216)
    01-12 15:09:46.299: W/System.err(377):  at org.apache.harmony.luni.net.PlainServerSocketImpl.create(PlainServerSocketImpl.java:40)
    01-12 15:09:46.299: W/System.err(377):  at java.net.ServerSocket.<init>(ServerSocket.java:120)
    01-12 15:09:46.299: W/System.err(377):  at java.net.ServerSocket.<init>(ServerSocket.java:74)
    01-12 15:09:46.299: W/System.err(377):  at com.phonegap.CallbackServer.run(CallbackServer.java:177)
    01-12 15:09:46.299: W/System.err(377):  at java.lang.Thread.run(Thread.java:1019)
    01-12 15:09:46.849: D/szipinf(377): Initializing inflate state
    01-12 15:09:46.849: D/szipinf(377): Initializing zlib to inflate
    01-12 15:09:46.869: D/szipinf(377): Initializing inflate state
    01-12 15:09:46.869: D/szipinf(377): Initializing zlib to inflate
    01-12 15:09:48.100: D/PhoneGapLog(377): file:///android_asset/www/index.html: Line 13 : ReferenceError: Can't find variable: onDeviceReady
    01-12 15:09:48.100: E/Web Console(377): ReferenceError: Can't find variable: onDeviceReady at file:///android_asset/www/index.html:13
    01-12 15:10:10.170: I/System.out(416): loadUrl(file:///android_asset/www/index.html)
    01-12 15:10:10.249: I/System.out(416): url=file:///android_asset/www/index.html baseUrl=file:///android_asset/www
    01-12 15:10:10.559: W/System.err(416): java.net.SocketException: Permission denied
    01-12 15:10:10.559: W/System.err(416):  at org.apache.harmony.luni.platform.OSNetworkSystem.socket(Native Method)
    01-12 15:10:10.559: W/System.err(416):  at dalvik.system.BlockGuard$WrappedNetworkSystem.socket(BlockGuard.java:335)
    01-12 15:10:10.569: W/System.err(416):  at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:216)
    01-12 15:10:10.569: W/System.err(416):  at org.apache.harmony.luni.net.PlainServerSocketImpl.create(PlainServerSocketImpl.java:40)
    01-12 15:10:10.569: W/System.err(416):  at java.net.ServerSocket.<init>(ServerSocket.java:120)
    01-12 15:10:10.569: W/System.err(416):  at java.net.ServerSocket.<init>(ServerSocket.java:74)
    01-12 15:10:10.569: W/System.err(416):  at com.phonegap.CallbackServer.run(CallbackServer.java:177)
    01-12 15:10:10.569: W/System.err(416):  at java.lang.Thread.run(Thread.java:1019)
    01-12 15:10:11.080: D/szipinf(416): Initializing inflate state
    01-12 15:10:11.080: D/szipinf(416): Initializing zlib to inflate
    01-12 15:10:11.100: D/szipinf(416): Initializing inflate state
    01-12 15:10:11.100: D/szipinf(416): Initializing zlib to inflate
    01-12 15:10:12.359: D/PhoneGapLog(416): file:///android_asset/www/index.html: Line 13 : ReferenceError: Can't find variable: onDeviceReady
    01-12 15:10:12.359: E/Web Console(416): ReferenceError: Can't find variable: onDeviceReady at file:///android_asset/www/index.html:13
    01-12 15:10:32.759: D/dalvikvm(416): GC_CONCURRENT freed 362K, 52% free 2806K/5767K, external 884K/1038K, paused 6ms+4ms
    01-12 15:11:42.329: D/dalvikvm(416): GC_CONCURRENT freed 489K, 54% free 2738K/5895K, external 884K/1038K, paused 6ms+3ms
    01-12 15:12:45.579: D/dalvikvm(416): GC_CONCURRENT freed 426K, 55% free 2696K/5895K, external 884K/1038K, paused 6ms+3ms

3 个答案:

答案 0 :(得分:0)

您提供的错误列表中列出了您的问题:

    01-12 15:10:12.359: E/Web Console(416): ReferenceError: Can't find variable:
        onDeviceReady at file:///android_asset/www/index.html:13

PhoneGap建议与标准DOM&lt; body onload /&gt;略有不同的型号。做法。您已使用以下命令绑定到设备就绪事件:

document.addEventListener("deviceready",onDeviceReady,false);

现在你需要实现'onDeviceReady'功能,例如,在&lt; script&gt;之间。标记:

function onDeviceReady() {
    alert("I'm ready!");
}

这将消除你的第一个问题;-)你可能会有另一个问题:

    01-12 15:08:52.230: W/System.err(338): java.net.SocketException:
        Permission denied

这是因为您正在加载的页面正在尝试访问其他服务器上的URL(http:192.168.1.3:8000 / index):这是您为html页面提供服务的地址吗?

答案 1 :(得分:0)

好的,第二个问题是你误解了jsonp。 Wikipedia很好地说明了这一点:

  

JSONP的请求不是JSON,而是任意JavaScript代码。   它们由JavaScript解释器评估,而不是由JSON解析   解析器。

如果您想使用successerror方法,则应该使用直接json作为dataType。这是一个非常基本的例子(请注意,因为它在代码中有console.log,所以不适用于IE - 如果您使用IE,只需删除这些行):

  <html>
    <head>
      <script src="js/jquery.js" ></script>
      <script language="javascript">
      $(function() {
        var output = $('#output');

        $.ajax( {
              url: "test.json",
              timeout: 5000,
              dataType: "json",
              success: function(data, status){
                  $.each(data, function(i,item){ 
                      var landmark = '<h1>'+item.name+'</h1>'
                      + '<p>'+item.latitude+'<br>'
                      + item.longitude+'</p>';

                      output.append(landmark);
                  });
              },
              error: function(err, textStatus, errorThrown) {
                 output.text("There was an error [" + textStatus + "] loading the data.");
                 console.log(err);
                 console.log(errorThrown);
              }      
        });
      });
      </script>
    </head>
  <body>
  <div id="output"></div>
  </body>
  </html>
我的服务器上的

和test.json看起来像这样:

  [
     { "name": "First", "latitude": 100, "longitude": 120 },
     { "name": "Second", "latitude": -23, "longitude": -20 },
     { "name": "Third", "latitude": 40, "longitude": 120 }
  ]

希望有所帮助,克雷格

答案 2 :(得分:0)

dataType jsonjsonp之间的区别在于json将返回将由JSON.parse解析的json数据,而jsonp将只检索并执行来自给定URL的javascript脚本(尽管它也会执行成功方法,如果有的话。)

因此,当使用jsonp时,我从服务器获取的数据将如下所示(我称之为testp.js):

jsonpCallback(
     [
        { "name": "First", "latitude": 100, "longitude": 120 },
        { "name": "Second", "latitude": -23, "longitude": -20 },
        { "name": "Third", "latitude": 40, "longitude": 120 }
     ]
);

我的testp.html就是:

  <html>
    <head>
      <script src="js/jquery.js" ></script>
      <script language="javascript">
      $(function() {
        var output = $('#output');

        $.ajax( {
              url: "testp.js",
              timeout: 5000,
              dataType: "jsonp",
              jsonpCallback: 'jsonpCallback',
              success: function(data, textStatus, jqXHR) {
                 alert('In success method');
              },
              error: function(err, textStatus, errorThrown){
                 output.text("There was an error [" + textStatus + "] loading the data.");
                 console.log(err);
                 console.log(errorThrown);
              }      
        });
      });

      function jsonpCallback(data) {
        var output = $('#output');
         $.each(data, function(i,item){ 
             var landmark = '<h1>'+item.name+'</h1>'
             + '<p>'+item.latitude+'<br>'
             + item.longitude+'</p>';

             output.append(landmark);
         });
     }
      </script>
    </head>
  <body>
  <div id="output"></div>
  </body>
  </html>

有两个要点:

  1. 使用jsonp时,我提供了我想用检索到的数据调用的函数的名称。 jQuery将此作为请求的一部分放入callback参数中,因此浏览器发出的请求为http://localhost/test/testp.js?callback=jsonpCallback&_=1326369112478。我的testp.js显然不应该对这个回调进行硬编码,而是使用提供的参数来调用适当的回调方法。

  2. 调用我的jsonpCallback函数时,success方法也被调用。但从逻辑上讲,根据我的示例,处理代码的正确位置在jsonpCallback方法中。

  3. jsonp优于json的优点是jsonp可以从托管发出请求的页面的服务器请求来自不同服务器的脚本。这允许跨站点脚本。