0

I had a problem when using servlet with jquery ajax. When I put the html file which contains the js code in the same project with the servlet, it will work. However, when I used this html on another machine and used the URL:http://192.168.1.5:8084/****/Servlet for the ajax, I could not get anything.

$.ajax({
   url:'http://192.168.1.5:8084/****/Servlet',
   data: ajaxdata,
   type:'GET',
   dataType:'text/html',
   //contentType: "text/html",
   success:function(json) { }
});

So any ideas? Thanks.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
jigsaw
  • 1
  • 1
  • 1

4 Answers4

3

If you have control over the servlet, set the HTTP Access-Control headers. This way you can control from the server side on whether the client who has fired the XMLHttpRequest is allowed to process the response. Any recent (and decent) webbrowser will take action accordingly.

Here's an example:

response.setHeader("Access-Control-Allow-Origin", "*"); // Everone may process the response.
response.setHeader("Access-Control-Allow-Methods", "GET"); // Commaseparated string of allowed request methods.

An alternative is JSONP, see also this article.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

!jigsaw

this is called same origin policy problem in ajax, It will work if both are on the same server.

read this link , its very nice

Ways to circumvent the same-origin policy

http://www.petefreitag.com/item/703.cfm

search in stack over flow you will get lot of answers

Community
  • 1
  • 1
kobe
  • 15,671
  • 15
  • 64
  • 91
  • Oh. thanks a lot. Do I have to use real webservice instead of servlet to achieve things like this? For example, you can get some data from a webservice URL – jigsaw Dec 12 '10 at 20:16
  • I understand. it's about ajax not service. Ajax has this "same origin" policy. But I can still access a servlet to get some data I need. – jigsaw Dec 12 '10 at 20:31
0

You cannot use AJAX to send a request to a different site.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

This is because you are making cross-domain ajax. Browsers tend to forbid this, because it is a security problem.

See here and here.

(Obviously, you will not have any problems when they are on the same server)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140