AJAX call doesnt work with RESTful web service?

2019-08-29 08:32发布

问题:

I have a simple restful service that returns a json. I want to make an ajax call to get required data. When I try with firefox's RestClient there is no problem. Service returns the json and I can see the json on rest client. But when I use ajax call it fails. The console shows 200 OK, but the error function executes after the call. I searched for this, commonly they say that its a cross domain problem but I fail to solve this.

This is the fail message of error function {"readyState":0,"responseText":"","status":0,"statusText":"error"}

AJAX call

$.ajax({
        type:"GET",
        url: "http://localhost:8080/myController/getInfo",
        dataType:"json",
        success: function(data){
            alert(JSON.stringify(data));
        },
        error: function(msg){
            alert("ERROR! \n" + JSON.stringify(msg));
        }
    });

Firefox's console message

Content-Type    application/json
Date    Mon, 18 Feb 2013 11:51:41 GMT
Server  Apache-Coyote/1.1
Transfer-Encoding   chunked

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3
Host    localhost:8080
Origin  null
User-Agent  Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0

The data returned from the call:

{ "date": "1 hour ago", "photoUrl": "img/movie_detail/celal.jpg", "rating": "three", "title": "Celal ile Ceren" } 

回答1:

It looks like you are violating the same origin policy restriction which prevents you from sending cross domain AJAX calls. You have used http://localhost:8080/myController/getInfo as url but this will only work if the HTML page containing this javascript was served from http://localhost:8080/. Otherwise the browser won't allow you to perform this AJAX call.

As a possible workaround you could modify your REST service so that it supports JSONP in addition to JSON. Then you will be able to send GET requests to it (POST doesn't work with jQuery's JSONP implementation because it is using a <script> tag).



回答2:

You can use CORS for this purpose.

Example code:

jQuery.support.cors = true; 

function CrosDom_ajax(url) {
        if (window.XDomainRequest
        && $.browser.msie
        && $.browser.version < 10) {
        xdr = new XDomainRequest();
        if (xdr) {
            xdr.onload = function () {
               alert(xdr.responseText);

            };
            xdr.open("get", url);
            xdr.send();
        }
        }
        else {
            $.ajax({
                url: url,
                success: function (response) {


                },
                error: function (data) {
                }
            });
         }
    }

Also you need to Write the following code in server side, to allow cross domain access

Response.AppendHeader("Access-Control-Allow-Origin", "*");


标签: ajax rest jquery