PhoneGap中的$ .getJSON无法正常工作

时间:2014-04-25 17:37:28

标签: 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();

运行上面的脚本时,我会看到以下警告:"Failure! Error: "error参数没有任何价值,因此我无法找到问题的实际位置。这个标题的大多数其他问题都有最好的答案,因为没有添加端点的域,我可以排除:

要查看我的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>

1 个答案:

答案 0 :(得分:1)

解决这个问题的方法:

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

Header set Access-Control-Allow-Origin "*"
相关问题