我在Javascript中有一个函数正在检查我的servlet:
function validate() {
var idField = document.getElementById("name1");
var data = "name1=" + encodeURIComponent(idField.value);
if (typeof XMLHttpRequest != "undefined") {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Validator"
req.open("POST", url, true);
req.onreadystatechange = inserter
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(data);
}
function inserter() {
if (req.readyState == 4) {
if (req.status == 200) {
var msg1 = req.responseText
if (msg1 == "") {
document.getElementById("msg").innerHTML = "<div style=\"color:red\">Wadliwa nazwa</div>";
document.getElementById("org").value = ''
}
else
document.getElementById("org").value = msg1
}
}
我发现: 指令
req.onreadystatechanged = inserter
设置负责处理服务器响应的函数。
动态更改页面内容的插入器函数将在服务器响应到达时异步调用。
在我的servlet上,我从我的网站获取参数:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("name1"));
if(!request.getParameter("name1").equals("")) {
serviceConnection(request, response);
}
}
不幸的是,当我尝试做同样的事情,但作为doGet,我根本无法做到......:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("name2"));
if(!request.getParameter("name2").equals("")) {
serviceConnection(request, response);
}
}
我试图将ajax的代码更改为:
var url = "Validator/?" + data2;
req.open("GET", url, true);
req.onreadystatechange = inserter2;
但它不起作用。 我怎么解决这个问题? 我应该做些什么而不是
req.onreadystatechanged = inserter 有一个doGet功能?
答案 0 :(得分:0)
尝试使用此代码..我纠正了它,因为你错了关闭括号,现在应该可以正常工作..
function validate() {
var idField = document.getElementById("name1");
var data = "name1=" + encodeURIComponent(idField.value);
if (typeof XMLHttpRequest != "undefined") {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "Validator"
req.open("GET", url, true);
req.onreadystatechange = inserter
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(data);
}
function inserter() {
if (req.readyState == 4) {
if (req.status == 200) {
var msg1 = req.responseText
if (msg1 == "") {
document.getElementById("msg").innerHTML = "<div style=\"color:red\">Wadliwa nazwa</div>";
document.getElementById("org").value = '';
} else {
document.getElementById("org").value = msg1;
}
}
}
}