AJAX不能调用回调函数 - Web 开发 / Ajax
一、页面 index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script language='javascript' src='js/jquery.js'></script>
</head>
<script type="text/javascript">
//使用JQuery方式
function verify2() {
var jqueryObj = $("#name");
var name = jqueryObj.val();
alert(name);
$.get("servlet/mytest?name=" + name, null, callback);
}
function callback(data) {
alert("xx");
}
</script>
<body>
我的第一个AJAX实例 用户名:
<input type="text" id="name" />
<input type="button" value="检测" onclick="verify2()" />
</body>
</html>
二、Servlet
package com.ajax.test;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 解决ajax返回值乱码问题
response.setContentType("text/xml;charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
System.out.println("用户名为" + name);
if ("".equals(name) || name == null) {
out.println("用户名不能为空");
} else {
if ("zyp".equals(name)) {
out.println("用户" + name + "已经存在");
} else {
out.println("用户" + name + "不存在,可以注册");
}
}
}
}
三、配置文件 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.ajax.test.MyServlet</servlet-class>
</servlet>
<servlet-mapping>