1

I started new project and added code for request. My js file looks like this:

(function () {
"use strict";

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

function onDeviceReady() {

    $.ajax({
        type: "GET",
        url: "http://api.vk.com/method/database.getCountries?v=5.5&need_all=0",
        crossDomain: true,
        success: function (response) {
            alert('Works!');
        },
        error: function (data) {
            console.log(data);
            alert('Not working!');
        }
    });

    // Handle the Cordova pause and resume events
    document.addEventListener( 'pause', onPause.bind( this ), false );
    document.addEventListener( 'resume', onResume.bind( this ), false );

    // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
    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;');
};

function onPause() {
    // TODO: This application has been suspended. Save application state here.
};

function onResume() {
    // TODO: This application has been reactivated. Restore application state here.
};
})();

But it didn't work at all. It always returns "Not working". I've tried other ways to send request but always get an error. Please, help!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
reagle
  • 11
  • 2

1 Answers1

1

Cordova 5.0 blocks external http requests by default.

Try adding cordova-plugin-whitelist to your project.

And rebuild your app still issue persist. Do one of following:

1) set following herder in your response service:

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

2) Add this line to config file -:

<access origin="*" />

3) additionally to the whitelisting, make sure the cors flag is true to enable cross origin resource sharing.

$.support.cors=true;

4) You can follow this $.getJSON for make request instead of ajax.

Hope it will help you.

Community
  • 1
  • 1
Naitik
  • 1,455
  • 15
  • 26
  • Thanks for answer, but it still not works. I made these steps that you wrote and nothing changes. – reagle Jul 14 '16 at 13:15
  • can you please replicate error which get at time of ajax call ? – Naitik Jul 14 '16 at 13:28
  • 2
    ajax were returning object with status = 0, but it does not matter. I solved the issue. I decided to use plugin "cordova-HTTP" and it helped me. I don't know how its work, but it works) Anyway thanks for trying to help – reagle Jul 14 '16 at 16:05