简体   繁体   English

如何使用ajax从javascript调用servlet

[英]how to call servlet from javascript using ajax

I am doing a samall jsp page to search a name enter in text box .. i called javascript function from jsp .. the bello is javascript code 我正在做一个samall jsp页面来搜索在文本框中输入的名称..我从jsp调用了javascript函数..贝娄是javascript代码

function fncStudsearch()
{
//alert("yes")
var ele=document.getElementById("stdSearch").value;
var xmlhttp;
var strAjUrlData="stdSearch?key="+ele;
//alert(strAjUrlData)
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
     xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.onreadystatechange=function()
 {
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

}
  else
  {
  alet(xmlhttp.status);
  }
 }
  xmlhttp.open("GET",strAjUrlData,true);
      xmlhttp.send();

  }

I am calling servlet .. and i configured web.xml as follows 我正在调用servlet ..并按如下方式配置了web.xml

   <servlet>  
      <servlet-name>stdSearch</servlet-name>
       <servlet-class>com.slokam.Act.StudentSearch</servlet-class>
  </servlet>

<servlet-mapping>
     <servlet-name>stdSearch</servlet-name>
     <url-pattern>/stdSearch</url-pattern>
</servlet-mapping>

</web-app>


I am unable ti go to servlet class and servlet code i have written is 我无法去我写的servlet类和servlet代码是

   public class StudentSearch extends HttpServlet {


   private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    String stdkey=request.getParameter("key");
    stdkey="%"+stdkey+"%" ;
    System.out.println(stdkey);
  }
}

please help in this regard how to goto servlet 请在这方面帮助如何转到servlet

If the app is not deployed as the root application on the appserver, you might need the context path in the url you are calling: 如果该应用程序未部署为应用程序服务器上的根应用程序,则可能需要在所调用的url中使用上下文路径:

var ctx = "${pageContext.request.contextPath}/";
var strAjUrlData=ctx+"stdSearch?key="+ele;

...

This code assumes you are using jsp 2.0 and EL 此代码假定您正在使用jsp 2.0和EL

Possibly this might help, there is an javascript error: 可能有帮助,可能是JavaScript错误:

alet(xmlhttp.status); // you're missing here `r`

alert(xmlhttp.status);

Secondly, you have to print out some contents from servlet, use PrintWriter for that. 其次,您必须从servlet中打印出一些内容,然后使用PrintWriter。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String stdkey=request.getParameter("key");
    stdkey="%"+stdkey+"%" ;
    // test purpose
    PrintWriter pw = response.getWriter ();
    pw.print(stdkey);
    pw.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM