2016-02-08 95 views
1

我有問題與cordova/phonegap/ajax來自網頁的請求。由於該應用正在與phonegap developer-app在手機上運行並完美地發送ajax requests。我認爲這跟permissions/plugins有什麼關係。但是,當我使用cordova安裝應用程序不發送任何東西,整個ajax request回報:Phonegap AJAX請求undefined

readyState: 0 
responseText: undefined 
status: 0 
text status: error 
error 

在​​3210我設置

<access origin="*" /> 

AndroidManifest.xml心中已經設定

<uses-permission android:name="android.permission.INTERNET" /> 

這裏是ajax request本身

$.ajax({ 
    method: "GET", 
    crossDomain: true, 
    dataType: 'json', 
    url: 'http://mywebsite.com/projectname/index.php', 
    data: { x: userLocation.latitude, y: userLocation.longitude }, 
    success: function(data){ 
     alert("Success: "+ data); 
    }, 
    error: function(xhr, textStatus, err) { 
     alert("readyState: " + xhr.readyState); 
     alert("responseText: "+ xhr.responseText); 
     alert("status: " + xhr.status); 
     alert("text status: " + textStatus); 
     alert("error: " + err); 
    } 
}); 

包括cordova.js到項目:

<script type="text/javascript" src="cordova.js"></script> 
<script src='js/jquery.js'></script> 
<script> 
    $(document).bind('mobileinit', function() { 
     $.mobile.changePage.defaults.changeHash = false; 
     $.mobile.hashListeningEnabled = false; 
     $.mobile.pushStateEnabled = false; 
    }); 
</script> 
<script ...here comes js file where ajax is called out 

設置這些沒有工作,要麼

$.support.cors = true; 
$.mobile.allowCrossDomainPages = true; 

回答

0

如果您正在運行科爾多瓦5或更高版本,則需要在內容安全策略meta標籤您的HTML,以便向外部服務器發出Ajax請求。如果你從一個較舊的Cordova版本開始升級到5或6,那麼你的index.html可能沒有其中的一個。如果您從CLI啓動了一個新的Cordova 5或6應用程序,那麼模板「Cordova Ready」應用程序將會有一個,但所提供的示例不允許向其他服務器發出Ajax請求,除非您明確配置它。

您可以添加這樣的事情到您的index.html,使Ajax請求的任何地方:

<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://api.fixer.io"> 

或者看一下如何配置在content-security-policy.com的Connect-SRC或我的博客文章here配置更嚴格的CSP適合您的需求。

此外,您可能希望使用Cordova「deviceready」事件而不是「mobileinit」,因爲在Cordova完全準備好之前您可能會過早地進行Ajax調用,所以在(onDeviceReady)回調函數中進行Ajax調用:

document.addEventListener('deviceready', this.onDeviceReady, false); 

或在調用之後執行的內容,表示Cordova已準備就緒。

0

顯然花了我很長時間才弄明白,所以繼承人如何得到它的工作: 首先我卸載項目中的所有插件,然後刪除文件夾平臺/ android。在CMD中鍵入:

cordova platform add android 

然後再次安裝必要的插件。 現在工作。