您的位置:首页 > 其它

ajax 异步刷新实例

2013-09-26 17:11 162 查看
1 在网上下载jquery.js

2 写第一个jsp页面

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
System.out.println("进入调用页面");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>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">
<script type = "text/javascript" src = "jquery.js"></script>         加入jquery.js文件,否则不能识别js中的那些格式
<script type="text/javascript" src = "query.js"></script>
</head>
<body>
This is my JSP pagess. <br>
name:<input type = "text" id = "name" name = "name" value = "myname"/><br/>
tel :<input type = "text" id = "tel" name = "tel" /><br/>
<input type = "button" id = "queryok" name = "queryok" value = "query" onclic = "query()"/>
</body>
</html>


query.js

$(document).ready(function(){
$("#queryok").click(function()
{
var oldname = $("#name").val();
$.ajax({
type: "post",          //请求方式
url: "query.jsp",      //请求页面路径
async:false,           //
cache:false,
data:                  //传过去的参数,可以通过request来取得
{
getname:"queryname",
gettel:"querytel"
},
dataType: "json",       //请求页面返回的字符串结果类型
success:function(datatmp)   //成功后,返回的结果存在datatmp变量中
{
$("#name").val(datatmp.name);
$("#tel").val(datatmp.tel);
},
error:function()
{
oldname = 'newsdd';
}
});
});
});


query.jsp 被访问的页面

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String myname = "wangdian";
String mytel = "123321";
String json = "{\"name\":\"" + myname + "\"," + "\"tel\":\"" + mytel + "\"}";
System.out.println("json:" + json);
out.print(json);
%>


index.jsp 页面->query.js触发访问->query.jsp 得到结果并返回到query.js中->使用返回的结果来回写index.jsp页面数据
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: