问题
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.
回答1:
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.
回答2:
!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
回答3:
You cannot use AJAX to send a request to a different site.
回答4:
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)
来源:https://stackoverflow.com/questions/4423693/jquery-ajax-with-servlet