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頁面數據


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章