首页 文章

在WP7 PhoneGap(Cordova)应用程序中使用$ .getJSON(v1.5)

提问于
浏览
2

我刚刚在iOS上完成了一个PhoneGap应用程序,现在是时候将它移植到WP7了 . 应用程序必须做的一件事是读取和解析JSON文件 .

$.getJSON("xml-json/myfile.json",function(data){ 
 // do cool things
});

但是当执行该行代码时,会抛出一些错误(无法调试,因此我不知道错误是什么),并且执行不会继续 . 知道那段代码有什么问题吗? That code works perfectly on the iOS version of PhoneGap.

This error is thrown in the Inmediate window: Log:"Wrapped XHR received Error from FileAPI :: [object Object]"

根据建议,我尝试使用$ .ajax而不是$ .getJSON . 并且代码在浏览器和iOS上完美运行,但在WP7中则不行 . 像这样简单的东西不起作用:

function onDeviceReady(){document.getElementById(“welcomeMsg”) . innerHTML =“Cordova已准备好!version =”window.device.cordova; console.log(“onDeviceReady . 您应该在Visual Studio的输出窗口中看到此消息 . ”);

navigator.notification.alert("readingjson");

        $.support.cors = true;

        $.ajax({
            url: "content2.json",
            dataType: 'json',
            context: document.body,
            success: function (a, b, c) {
                navigator.notification.alert("json readed");
            }
        });

        navigator.notification.alert('yeah');
    }

“readjson”警报被解雇了,“是的”,但是“json readed”一个人被解雇了......

谢谢!

6 回答

  • 0

    您没有说明您使用的是哪个Cordova版本,但是,v1.4中存在一个相当大的错误,这意味着XHR请求失败 . 这已在v1.5中修复 - 请参阅此JIRA错误:

    https://issues.apache.org/jira/browse/CB-208

    如果你使用1.5仍然看到问题,这可能是一个新的错误!

  • 0

    与$ .support.cors一起,您还需要将$ .mobile.allowCrossDomainPages设置为true .

    检查jQuery Mobile Docs

  • 1

    您对错误等没有特别的了解,但在JSON调用之前尝试设置以下属性:

    $.support.cors = true;
    
  • 3

    我使用cordova 2.7.0,我有同样的问题 .

    这不是一个错误,但这是一个适合我的解决方案:

    • 将您的javascript代码移动到单独的文件并将其包含在您的html中,以避免烦人的Visual Studio html检查器 .

    • 在ajax调用之前放"$.support.cors = true;" . 我把它包含在deviceready函数中 .

    • 不要按照之前的答案建议"$.mobile.allowCrossDomainPages = true;" . 在我的情况下,这一行导致应用程序挂起 .

    我的代码看起来像这样:

    的index.html

    <script type="text/javascript" src="js/content.js"></script>
    <script type="text/javascript">
      document.addEventListener("deviceready", onDeviceReady, false);
    
      function onDeviceReady() {
        $.support.cors = true; 
        getContents();
      }
    </script>
    

    contents.js

    function getContents() {
        $.ajax({
    url:"http://www.xxx.com/?getSomething",
        dataType:"json",
        error:function(xhr, status, errorThrown) {
        navigator.notification.alert('Failed', function(){}, 'Info', 'OK');
        },
        success:function(data) {
        navigator.notification.alert('Success!', function(){}, 'Info', 'OK');
        }
    });
    }
    

    原谅我的英语 .

  • 0

    尝试本机ajax调用这将解决问题 .

    至少它为我做了 .

    〜ķ

  • 1

    你说你无法获得调试信息,你使用的是PhoneGap Build吗?否则,您应该在Visual Studio的“输出”窗口中看到来自应用程序的日志记录(确保显示“调试”的输出) .

    如果您只是将PhoneGap与Visual Studio一起使用,请确保JSON文件作为内容项包含在项目中,并且在构建时使用这些项更新CordovaSourceDictionary.xml文件 .

    见:https://stackoverflow.com/a/8902502/1441046

相关问题