Make AJAX call in AngularJS in Cordova App

2019-06-03 15:42发布

问题:

I have built an app using Ionic Framework, AngularJS, and Cordova. In it, I have made AJAX calls to several php files using $http.get(), which works perfectly in a browser, but not within the app. The app is able to render internet pages through an iframe so the network is working. I have whitelisted my server where the php files reside inside of the app.js file and using . Also, in my php files I've added header('Access-Control-Allow-Origin: *');

Any suggestions on how to get this AJAX call to work?

.controller('StuffCtrl', function($scope, StuffService, LoadingService) {
    StuffService.getStuff().then(function(data) {
        LoadingService.show();
        $scope.stuff = data;
        LoadingService.hide();
    });
})

.service('StuffService', function($http){
    var myStuff;
    return {
        getStuff: function(){
            return $http.get('http://mydomain/stuff.php').then(function(items) { 
                myStuff = items.data; return myStuff; 
            });
        }
    });
});

回答1:

I had the same error while working on a hybrid app and then I added these lines in my route config function and it started working

$httpProvider.defaults.useXDomain=true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

This is to enable CORS. More info on the same can be found here



回答2:

Add a catch handler to get the error :

StuffService.getStuff().then(function(data) {
        LoadingService.show();
        $scope.stuff = data;
        LoadingService.hide();
    }).catch(function(error){
         $scope.error = error;
    });

And pretty display the error :

<pre>{{error|json}}</pre>

This should tell you what is going on.