ajax 异步刷新实例

前端之家收集整理的这篇文章主要介绍了ajax 异步刷新实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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页面数据

猜你在找的Ajax相关文章