小编典典
这里,需要对JavaScript函数进行校正。当您说时var
xmlHttp,它在函数内部有作用域,ajaxEditFunctionCall而不是在作用域内showMessage。另外,xmlhttpin
showMessage()与中的xmlHttpobject不同ajaxEditFunctionCall。因此,使var
xmlHttp声明保持全局并进行更正。这是工作代码:
var xmlHttp;
function ajaxEditFunctionCall(){
var URL = "ajaxcall.action?stateName=State1";
try{
xmlHttp=new XMLHttpRequest();
}catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
//alert(1);
xmlHttp.onreadystatechange = showMessage;
//alert(2);
xmlHttp.open("GET", URL, true);
//alert(3);
xmlHttp.send(null);
}
function showMessage() {
//alert("Inside Show Message1");
//alert(xmlHttp.readyState);
if(xmlHttp.readyState==4)
{
alert("Inside Show Message2&ReadyState4");
alert(xmlHttp.responseText);
}
}
Java代码是:
public class CustomerAction extends ActionSupport implements ServletResponseAware {
HttpServletResponse response;
public String ajaxcall() {
System.out.println("Inside AjaxCall");
String errorXml = "This is a Sample to Check";
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
try {
response.getWriter().write(errorXml);
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
}
struts.xml是:
/pages/customer/addCustomer.jsp
2020-06-08