1

We have implemented webservice which generates xml response.

I am facing issue while invoking it through the jquery ajax.

If I put same file within the same container I am getting a proper response. This is because of the cross domain policy.

Please suggest me how to use cross domain policy in jquery ajax?

I am using tomcat as a webserver. All webservices are deployed on this server.

Below is the code.

function doajaxcall() 
{
$.ajax({
    url: "http://localhost:8080/mobile-services/rest/languages/",
    type: "GET",
    processdata: true,
    dataType: "json",
    contentType: "application/json;",
    beforeSend: function () { },
    headers : 
    {
        "Content-Type"  : "application/json",
        "Accept" : "application/json",
        "Access-Control-Allow-Origin":"http://192.168.0.1:8080/"
    },
    success: function (data) 
    {          
        alert('Data..'+data);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) 
    {
        try 
        {
            alert(JSON.stringify(XMLHttpRequest) + "\n" + textStatus + "\n" + errorThrown);
        }
        catch (ex) { alert("Exception occured.. "); }
        finally { }
    }
});

}

If i run this code from the same container in header i am getting "Access-Control-Allow-Origin":"http://192.168.0.1:8080/" in header.

If i run it outside of the container i am getting

"Access-Control-Allow-Origin":null

Please suggest.

Chetan Shirke
  • 896
  • 4
  • 13
  • 35

2 Answers2

2

To fix this issue. I have added cors-filter-1.3.1.jar to webservices/web-inf/lib. directory.

below is the web.xml file configuration to enable cross domain access for tomcat.

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>

<filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

Changed the response type of spring 3.0 webservices from xml to JSON. I am using following code snippet to read JSON data from the webservice.

$.getJSON('http://localhost:8080/mobile-services/rest/languages/',
function(data) 
{
    $("#lang_1").html(data.languages[0].language);
    $("#lang_2").html(data.languages[1].language);
    $("#lang_3").html(data.languages[2].language); 
});
Chetan Shirke
  • 896
  • 4
  • 13
  • 35
1

Use JSONP (JSON with padding) as the dataType for cross-domain requests.

For example:

(function($) {
var url = 'http://localhost:8080/mobile-services/rest/languages/test.json?callback=?';

  $.ajax({
   type: 'GET',
   url: url,
   async: false,
   jsonpCallback: 'jsonCallback',
   contentType: "application/json",
   dataType: 'jsonp',
   success: function(json) {

   //your code
    },
 error: function(e) {
   console.log(e.message);
 }
 });
 })(jQuery);
Ravi Kadaboina
  • 8,494
  • 3
  • 30
  • 42