<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
function fun(){
/*创建ajax引擎对象*/
var xmlHttp = new XMLHttpRequest();
//绑定监听
xmlHttp.onreadystatechange = function(){
//接受相应的数据
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var res = xmlHttp.responseText;
$("#p").html(res)
}
}
//绑定地址 true 为异步 false 为同步
xmlHttp.open("POST","/WEB22/AJAXServlet",true)
//get请求不用这个
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//发送请求
xmlHttp.send("name=zzzz");
}
</script>
<body>
<div><p id="p">Hello</p></div>
</body>
</html>
JQuery的AJAX代码
onload = function() {
$.post(
"/WEB20/ajaxServlet", //要访问的地址
{"name":"李四","age":10}, //传递的值
function(data){
//返回成功要执行的方法
alert(data.name)
},
"json" //返回值类型
)
//目前感觉应该这两个没啥区别
$.get(
"/WEB20/ajaxServlet", //要访问的地址
{"name":"李四","age":10}, //传递的值
function(data){
//返回成功要执行的方法
alert(data.name)
},
"json" //返回值类型
)
}
往回传递的时候需要加转义
response.getWriter().write("{\"name\":\"tom\",\"age\":\"21\"}");