javascript - PhoneGap 中的 $.getJSON 不工作

标签 javascript jquery linux ubuntu cordova

var app = {
    // Application Constructor
    initialize: function() {
        $.getJSON( "http://domain.com/api/data")
          .done(function( json ) {
            alert("SUCCESS!");
          })
          .fail(function( jqxhr, textStatus, error ) {
            alert("Failure! Error: " + error);
        });
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

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

        console.log('Received Event: ' + id);
    }
};

app.initialize();

运行上面的脚本时,我看到以下警告:“失败!错误:”error 参数没有任何值(value),所以我很难找到问题所在。大多数具有此标题的其他问题都有最佳答案,因为没有添加端点的域,我可以排除这种情况:

要查看我的 config.xml 文件,请单击 here .

您会看到我设置了 origin="*",它应该允许与所有端点通信,无论是哪个域。关于为什么会发生这种情况的任何想法?

更新

这与我的服务器有关,因为其他服务器显示“SUCCESS”警报消息。不过,仍未找到具体问题。出于某种原因,我的服务器似乎不喜欢跨源请求......我已经禁用了防火墙但没有成功。只是想确认请求在同一 URL 上时工作得很好。

启用服务器站点/000-default.conf:

<VirtualHost *:80>
    Header add Access-Control-Allow-Origin "*"
    Header add Access-Control-Allow-Methods "GET, OPTIONS"

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

最佳答案

解决方法:

在服务器上的 .htaccess 中,添加这一行

Header set Access-Control-Allow-Origin "*"

关于javascript - PhoneGap 中的 $.getJSON 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23299590/

相关文章:

c++ - 在 Linux 上测试按键是否被按下而不阻塞

javascript - 将数据附加到本地存储问题

javascript - jQuery replaceWith 删除我的 :after pseudoelement

javascript - JQUERY.计数.JS : On Scroll Count Numbers NOT OnLoad

linux - Shell 变量扩展 - 使用 env 调用实用程序时的间接寻址

c - Linux 上的 <conio.h> 头文件在哪里?为什么找不到 <conio.h>?

javascript - AngularJS:使用相同输入添加和编辑列表项

javascript - 在 JavaScript 中转置二维数组

javascript - 支持地理定位但不起作用

javascript - 如何使用 jquery ui sortable 对使用 Material 设计创建的 Angular 选项卡进行排序?