如何通过AJAX从javascript调用servlet

时间:2014-08-14 06:37:49

标签: javascript ajax servlets

我有一个类似下面的JavaScript函数

function ProviderSearchRequest()
{
    var LegacyUserID    = g_PQContactTree.selectSingleNode( " /LegacyLogin" ).text;
    var LegacyPassword  = g_PQContactTree.selectSingleNode( " /LegacyPassword" ).text;   
}

我的服务

public class AWDB2BAuthentication extends HttpServlet {
     public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
          IOException {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        out.println("User Name: " + req.getRemoteUser());
        String name = (req.getUserPrincipal() == null) ? null : req.getUserPrincipal().getName();
        out.println("Principal Name: " + name);
        out.println("Authentication Type: " + req.getAuthType());
        out.println("Hello World..... ");
      } 

如何使用AJAX通过java函数调用servlet?

2 个答案:

答案 0 :(得分:0)

首先,您需要在WEB-INF文件夹中的web.xml中为您的servlet定义url映射,然后通过jquery调用您的servlet,如下所示:

function getData(){
   var xhr=$.ajax({url:"Servlet Path",type:"GET",
   success:function(data){
      console.log(data);
   }
 });
}

$(document).ready(function(){
   getData();
});

答案 1 :(得分:0)

感谢@Super Hornet你的时间。如果我们设置$ .support.cors = true; Ajax跨浏览器问题将得到解决