$.getJSON 可以与 PhoneGap 构建一起使用吗?

Will $.getJSON work with PhoneGap build?

有人能在他们的 PhoneGap 版本中使用它吗? :

$(function(){
    $.getJSON("http://reddit.com/.json", function(data){
        alert("Success!");
    })
})

它在浏览器中工作正常,但当我构建应用程序时它不 运行。

我已经将这些添加到我的 config.xml 中以将所有域列入白名单

<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
<allow-navigation href="data:*" />
<allow-navigation href="*" />
<access origin="*" />
<allow-intent href="*" />

还尝试使用此 CSP 构建它,但不使用

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *">

我从这里得到的:https://github.com/apache/cordova-plugin-whitelist

我查看了这个并在我自己的 PhoneGap Build 项目中复制了您的 Ajax 请求。

我注意到 URL 您正在使用 http://reddit.com/.json seems to get redirected on Android devices at least to https://www.reddit.com/.json

我通过在打开调试的情况下进行 PhoneGap Build 构建发现了这一点,运行 Nexus 7 上的 .apk 附加了 Chrome 远程调试器工具,并在 JS 控制台中看到了这一点:

"Refused to connect to 'https://www.reddit.com/.json' because it violates the following Content Security Policy..."

我通过修改 index.html 中的内容安全策略元标记以在 connect-src 子句中包含两个 https://www.reddit.com and http://reddit.com 来解决此问题。使用此 CSP 在 PhoneGap Build 上重建,它现在在 Nexus 7 上运行良好:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; connect-src http://reddit.com https://www.reddit.com">

所以我的 PhoneGap 应用程序现在看起来像这样并且可以运行:

var app = {
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },

    onDeviceReady: function() {
        var parentElement = document.getElementById('deviceready');
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        $.getJSON('http://reddit.com/.json', function(data){
            alert('Success - got ' + data.data.children.length + ' children in JSON');
        });
    }
};

app.initialize();

为了您的方便,我将完整的应用程序准备好用于 PhoneGap Build 中的 Github 存储库 here。请根据需要随意使用它。