Ajax 的几种方法应用
一,js实现ajax异步请求,简单例子
try.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'try.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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function showHint(str)
{
var xmlhttp;
if (str.length==0){
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","LoginServlet?op="+str,true);
xmlhttp.send(null);
}
</script>
</head> <body>
<h3>请在下面的输入框中键入字母(A - Z):</h3>
<form action="">
姓氏:<input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>建议:<span id="txtHint"></span></p>
</body>
</html>
LoginServlet
最后启动服务器,访问try.jsp 输出 a ,即可马上出现 apple
package com.dkt.servlet; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import com.dkt.dao.UserJdbc; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
String op = request.getParameter("op");
System.out.println("op----------->"+op);
if (("a").equals(op)) {
request.setAttribute("aaa", "apple");
PrintWriter out = response.getWriter();
out.print("apple");//responseText;
out.flush();
out.close();
} } }
二,ajax 在 jquery 中封装后的应用 的 get(),post() 方法
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'ajax.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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> <script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("input[name='so']").click(function(){
/* // ajax
$.ajax({
url:"AjaxSer",
type:"post",
data:{
one:$("input[name='one']").val(),
two:$("input[name='two']").val()
},
dataType:"json",
// arg是个集合
success:function(arg){
$.each(arg,function(i,item){
var temp = "<tr><td>"+item.id+"</td><td>"+item.name+"</td><td>"+item.password+"</td><td>"+item.email+"</td><td>"+item.telphone+"</td></tr>";
$("table").append(temp);
});
}
}); */ /* // get()方法 form表单中submit会提交表单,就会刷新页面。1,阻止表单提交 2,submit改为button
$.get("AjaxSer",
$("form").serialize(),
function(arg){
alert("get方法,只有请求成功才执行回执函数1");
$.each(arg,function(i,item){
var temp = "<tr><td>"+item.id+"</td><td>"+item.name+"</td><td>"+item.password+"</td><td>"+item.email+"</td><td>"+item.telphone+"</td></tr>";
$("table").append(temp);
});
},"json");*/ // post方法
$.post("AjaxSer",
{one:$("input[name='one']").val(),two:$("input[name='two']").val()},
function(arg){
$.each(arg,function(i,item){
var temp = "<tr><td>"+item.id+"</td><td>"+item.name+"</td><td>"+item.password+"</td><td>"+item.email+"</td><td>"+item.telphone+"</td></tr>";
$("table").append(temp);
});
},"json"); });
// ajax 加载html文件
$("#loadBt").click(function(){
$("#load").load("ind.jsp",{name:"小白",sex:"女"},function(){alert("加载完毕,请求成功与否都执行!");});
}); }); </script>
</head> <body>
<form>
条件一:姓名<input type="text" name="one" value=""/>
条件二:电话<input type="text" name="two" value=""/><br/>
爱好:<input type="checkbox" value="吃饭" name="hobby">吃饭
<input type="checkbox" value="睡觉" name="hobby">睡觉
<input type="checkbox" value="打豆豆" name="hobby">打豆豆
<input type="checkbox" value="玩游戏" name="hobby">玩游戏
<input type="button" value="检索" name="so">
</form>
<table border="1px" width="50%" height="200px">
<th>学号</th>
<th>姓名</th>
<th>密码</th>
<th>邮箱</th>
<th>电话</th>
</table>
<button id="loadBt" type="button">加载html文件</button>
<div id="load"></div>
</body>
</html>
加载的 ind.jsp 页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My 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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body> <%
String name= request.getParameter("name");
String sex = request.getParameter("sex");
request.setAttribute("name",name);
request.setAttribute("sex",sex);
%>
得到的参数:姓名:${name }<br/>
性别:${sex }
</body>
</html>
后台接受ajax传送的数据和响应页面
package com.direct.servlet; import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.direct.dao.SosAjax;
import com.direct.entity.UserInfo;
import com.google.gson.Gson; public class AjaxSer extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String one = request.getParameter("one");
String two = request.getParameter("two");
/* String[] hobby = request.getParameterValues("hobby");
// hobby = new String(hobby.getBytes("iso-8859-1"), "utf-8");
// System.out.println("hobby--------->"+hobby); for (String str : hobby) {
str = new String(str.getBytes("iso-8859-1"), "utf-8");
System.out.println("爱好:"+str);
}*/
// one = new String(one.getBytes("iso-8859-1"), "utf-8"); 此句get()时用
System.out.println(one);
System.out.println(two);
ArrayList<UserInfo> list = new SosAjax().validate(two, one);
Gson gson = new Gson();
String json = gson.toJson(list);//直接转化成json格式
System.out.println(json); out.print(json);//响应ajax异步请求
out.flush();
out.close();
} }
三,jsonp的简单实现ajax跨域请求
http://localhost:8082/webAjax/js/web.js
$(function(){
cross_domain({content:"跨域取值"})
})
本项目下的jsp jsonp.jsp
引入上面的web.js
需要两个项目同时开启服务器
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'jsonp.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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="js/jquery.js"></script><%--这句必须放在第一行,不然就不能使用$ --%>
<script type="text/javascript" src="http://localhost:8082/webAjax/js/web.js"></script>
<script type="text/javascript">
alert("hahah");
var web = function(data){
alert("jsonp中传来的js值----"+data.content);
} $(function(){
$.ajax({
async:"false",
type:"post",
url:"http://localhost:8082/webAjax/JsonpSer", // 请求到跨域
dataType:"jsonp",
// 传递给请求处理程序或者动态页面的变量名称,用于获取回调函数名称
jsonp:"callback",
// 自定义json回调函数,默认jQuery自动生成的随机数
jsonpCallback:"fuliWeb",
success:function(da){
alert(da.name);
},
error:function(){
alert("请求出错!1");
}
}); }); </script>
</head> <body>
This is my JSP page. <br>
</body>
</html>
Ajax 的几种方法应用的更多相关文章
- jquery实现AJAX的4种方法
当我们用javascript写ajax程序写得很“开心”的时候,突然有人告诉你有一种东西叫jquery,它会告诉你不直接和 HttpRequest是多么的快乐,同时你再也不需要再烦恼纠结的ajax乱码 ...
- MVC异步AJAX的三种方法(JQuery的Get方法、JQuery的Post方法和微软自带的异步方法)
异步是我们在网站开发过程中必不可少的方法,MVC框架的异步方法也有很多,这里介绍三种方法: 一.JQuery的Get方法 view @{ Layout = null; } <!DOCTYPE h ...
- ajax 使用 三种方法 设置csrf_token的装饰器
1. CSRF中间件 CSRF跨站请求伪造 2. 补充两个装饰器 from django.views.decorators.csrf import csrf_exempt, csrf_prote ...
- javascript实现原生ajax的几种方法介绍
自从javascript有了各种框架之后,比如jquery,使用ajax已经变的相当简单了.但有时候为了追求简洁,可能项目中不需要加载jquery这种庞大的js插件.但又要使用到ajax这种功能该如何 ...
- AJAX实现跨域的三种方法
由于在工作中需要使用AJAX请求其他域名下的请求,但是会出现拒绝访问的情况,这是因为基于安全的考虑,AJAX只能访问本地的资源,而不能跨域访问. 比如说你的网站域名是aaa.com,想要通过AJAX请 ...
- Ajax跨域的几种方法以及每种方法的原理
js中几种实用的跨域方法原理详解 这里说的js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据.只要协 ...
- ajax异步提交的两种方法
第一种是原始的ajax,第二种是在jQuery中使用ajax.这是我为测试两种提交方法而写的一段代码. 1.struts.xml <package name="json" e ...
- ASP.NET MVC 实现AJAX跨域请求的两种方法
通常发送AJAX请求都是在本域内完成的,也就是向本域内的某个URL发送请求,完成部分页面的刷新.但有的时候需要向其它域发送AJAX请求,完成数据的加载,例如Google. 在ASP.NET MVC 框 ...
- struts2实现ajax校验的2种方法
共同的一点是,Action都需要将一个方法暴露出来,给前端javascript调用 javascript的代码都是一样的: Js代码 function testAjax() { var $use ...
随机推荐
- mysql编写存储过程(2)
书接上回. 实例8:if-then -else语句 实例9:case语句: 实例10:循环语句,while ···· end while: 实例11:循环语句,repeat···· end repea ...
- Window History对象
History 对象属性 length 返回浏览器历史列表中的 URL 数量. History 对象方法 back() 加载 history 列表中的前一个 URL. window.history.b ...
- Liunx-history命令
1. 查看历史命令执行记录 2. 查看命令cd 的历史执行记录 3. 执行历史记录中,序号为1的命令
- 剑指offer二十九之最小的K个数
一.题目 输入n个整数,找出其中最小的K个数.例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,. 二.思路 详解代码. 三.代码 import java.util. ...
- django框架--底层架构
目录 零.参考 一.对于web服务的理解 二.对于wsgi协议的理解 三.自定义一个简单的基于wsgi协议的web框架 四.django中的server实现 五.django中的application ...
- CDH版本大数据集群下搭建Hue(hadoop-2.6.0-cdh5.5.4.gz + hue-3.9.0-cdh5.5.4.tar.gz)(博主推荐)
不多说,直接上干货! 我的集群机器情况是 bigdatamaster(192.168.80.10).bigdataslave1(192.168.80.11)和bigdataslave2(192.168 ...
- vsts~CI/CD实现自动化编译
打开你的vs online,选择build and release标签,进行自动化编译的开发. 一 新建,选择对应的源代码管理,我们以VSTS-GIT为例 二 选择你的项目所应对的开发框架,如.net ...
- hexo上部署博客到Github失败
fatal: could not read Username for 'https://github.com': No error 今天在上传博客到搭建到 Github 的个人博客上的时候,已经使用 ...
- tomcat安装以及常用配置
目录 一 什么是tomcat 二 tomcat 的版本: 三 tomcat的下载 3.1 tomcat9版本下载链接 3.2 tomcat8.5版本下载链接 四 tomcat的安装 4.1 java环 ...
- Hive文件存储格式和hive数据压缩
一.存储格式行存储和列存储 二.Hive文件存储格式 三.创建语句和压缩 一.存储格式行存储和列存储 行存储可以理解为一条记录存储一行,通过条件能够查询一整行数据. 列存储,以字段聚集存储,可以理解为 ...