[英]how to call servlet from javascript using ajax
我正在做一個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();
}
我正在調用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>
我無法去我寫的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);
}
}
請在這方面幫助如何轉到servlet
如果該應用程序未部署為應用程序服務器上的根應用程序,則可能需要在所調用的url中使用上下文路徑:
var ctx = "${pageContext.request.contextPath}/";
var strAjUrlData=ctx+"stdSearch?key="+ele;
...
此代碼假定您正在使用jsp 2.0和EL
可能有幫助,可能是JavaScript錯誤:
alet(xmlhttp.status); // you're missing here `r`
alert(xmlhttp.status);
其次,您必須從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.