5-jQuery - AJAX get()/post()页面请求即执行
get
前台页面
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script> <title></title> <style type="text/css"> #dsh{width: 100%; height: 100px; border: red solid 1px;} </style> </head> <body> <div id="dsh"></div> <script type="text/javascript"> $.ajax({ type: "get", url: "Test.jsp", success: function (data) {document.getElementById("dsh").innerHTML=data;}, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown);} }); </script> </body> </html>
后台页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ page import="java.io.PrintWriter" %> <!DOCTYPE HTML> <html> <head></head> <body> This is my JSP page. <br> <% PrintWriter out2=response.getWriter(); out2.println("Hello dsh!");//out2是response的实例 out2.flush();//输出流的方法,清空缓冲区 out2.close();//关闭输出流 %> </body> </html>
打开就已经加载进来了
Post
前台页面
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script> <title></title> <style type="text/css"> #dsh{width: 100%; height: 100px; border: red solid 1px;} </style> </head> <body> <div id="dsh"></div> <script type="text/javascript"> $.ajax({ type: "post", url: "Test.jsp", data:{Name:"sanmao",Password:"sanmaoword"}, datatype: "html",//"xml", "html", "script", "json", "jsonp", "text". success: function (data,status) {alert("Data: " + data + "\nStatus: " + status);}, error: function (data,status) { alert("请求出错"+"\n"+"\nStatus: " + status);} //还有一些其它方法 //beforeSend:function(){alert("在请求之前调用的函数")}; //complete: function(){alert("在调用执行后调用的函数")} }) </script> </body> </html>
后台页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ page import="java.io.PrintWriter" %> <!DOCTYPE HTML> <html> <head></head> <body> 我是后台页面,此页不要单独打开,否则值为空<br/> 接受到的值是:<%=request.getParameter("Name")%> </body> </html>
执行