jQuery的AJAX使用ServletjQuery、AJAX、Servlet

2023-09-10 19:02:11 作者:Momentary 短暂

我使用的servlet用jQuery Ajax时出现了问题。当我把它包含了JS code与servlet的同一项目的HTML文件,它会奏效。然而,当我使用这个网站上的另一台机器和使用的URL: http://192.168.1.5:8084/****/Servlet 的阿贾克斯,我可以没有得到任何东西。

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.

推荐答案

如果您在servlet的具有控制,设置的 HTTP 访问控制 头。这样你可以从服务器端是否在客户端上控制谁打响了XMLHtt prequest被允许处理响应。任何最近的(和体面)web浏览器将采取相应措施。

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.

下面是一个例子:

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

另一种方法是 JSONP ,也见的这篇文章。