嗨我在我的程序中试用基于servlet的ajax我使用带有按钮和文本框的html页面当我点击按钮它应该向服务器发出一些ajax请求完成一些计算并返回结果在同一页面
<html>
<head>
<title></title>
</head>
<body>
<h3>Ajax in servlets</h3>
<div id="change"> hi there</div>
<input type="text" id="fname" name="solo">
<input type="button" align="center" value="Ajax" onclick="ajaxreq()" />
</body>
</html>
在这个html页面中一个文本框和一个按钮当我点击按钮时它应该执行以下java脚本函数
var xmlreq=null;
var a=document.getElementById("fname");
function ajaxreq(){
if(window.XMLHttpRequest){
xmlreq=new XMLHttpRequest();
}
else if(window.ActiveXObject){
xmlreq=new ActiveXObject("Microsoft.XMLHTTP");
}
try{
xmlreq.onreadystatechange=response;
xmlreq.open("GET","Servlethello?an=+a",true);
xmlreq.send();
}
catch(e){
alert("some error")
}
}
function response(){
var res=xmlreq.responseText;
document.write(res);
alert(res);
document.getElementById("change").innerHTML=res;
}
</script>
here i have created a ajax call and send the request to the servlet Servlethello
public class Servlethello extends HttpServlet {
@Override
public void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>");
String a=req.getParameter(an);
out.println("solorules"+a);
out.println("</h1>");
out.close();
}
}
变量a获取在文本框中输入的值并将其发送到servlet xmlreq.open(&#34; GET&#34;&#34; Servlethello一个= + A&#34;,TRUE);到这个servlet
public void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>");
String a=req.getParameter(an);
out.println("solorules"+a);
out.println("</h1>");
这个servlet应该显示在这里 你好,使用这个java脚本
var res=xmlreq.responseText;
document.write(res);
alert(res);
document.getElementById("change").innerHTML=res;
答案 0 :(得分:1)
你可以使用jquery ajax,它非常简单而不是纯粹的JS ajax。
请参阅以下链接 http://api.jquery.com/jquery.ajax/
示例代码:
$.ajax({
url: "test.html",
dataType:"html"
context: document.body
}).done(function(res) {
alert(res);
});
使用Pure JS:
var xmlhttp;
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)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
有关详细信息,请参阅链接: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
答案 1 :(得分:0)
您可以使用以下示例jquery脚本进行ajax调用
function makeAjaxCall(){
$.ajax({
var data = ""; // if you want to pass data as request param then assign here
url: // your servelt path here......,
type: 'GET',
cache: false,
data: data,
success: function (data) {
alert(data);
},
error: function (data, status, er) {
alert(er);
}
});
}