Error when trying to get JSON data from a web service

591 Views Asked by At

My customer provided me a webservice link return a json data. I browsed it and get a good result. But when I created a simple html page and using jquery ajax

        var myCallback = function (data) {
            alert("Data:" + data);
        };

var url = "http://xxx/getToken";        

var params = { username: "abc", password: "123" }

        $.ajax({
            type: "GET",
            url: url,
            data: params,
            contentType: "text/plain",
            dataType: 'jsonp',
            crossDomain: true,
            cache: false,
            success: myCallback,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
                alert(XMLHttpRequest.responseText);
            },
            async: false
        });

It always return error "NetWorkError" but I tracked the result from FIDDLE, the result shown as like a browser ???

And when I change url for example to:

        var url = "http://api.openweathermap.org/data/2.5/weather";
        var params = { lat: "35", lon: "139" }

It works well!....I don't know what exactly the problem is the IIS configuration or Jquery Ajax library.

Do you have some solution to solve this problem?

Thanks!!!

2

There are 2 best solutions below

2
On

The problem is that you
A) use JSONP where you should use JSON,
JSONP is just a technique of sending JSON-data
B) async is set off, so your broswer expects an response at the moment it sends the request,
This while it should be waiting for a response.

So try this

   var myCallback = function (data) {
        alert("Data:" + data);
    };
var url = "http://xxx/getToken";        
var params = { username: "abc", password: "123" }
    $.ajax({
        type: "GET",
        url: url,
        data: params,
        contentType: "text/plain",
        dataType: 'json',
        crossDomain: true,
        cache: false,
        success: myCallback,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
            alert(XMLHttpRequest.responseText);
        },
        async: true
    });
0
On

Finally, I have found a solution to solve this problem. The main problem here is the cross site access data policy. My customer's api service was not included:

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST

So, the browser does not allow my ajax request to get a json data. Manually, I have to turn on a setting located in (IE) Internet Setting -> Miscellaneous -> Access Data Sources across domain (set it enable) to get a data

Conclusion, we have to add these to header for a priority then the browser setting in case of without these in a header