一,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 的几种方法应用的更多相关文章

  1. jquery实现AJAX的4种方法

    当我们用javascript写ajax程序写得很“开心”的时候,突然有人告诉你有一种东西叫jquery,它会告诉你不直接和 HttpRequest是多么的快乐,同时你再也不需要再烦恼纠结的ajax乱码 ...

  2. MVC异步AJAX的三种方法(JQuery的Get方法、JQuery的Post方法和微软自带的异步方法)

    异步是我们在网站开发过程中必不可少的方法,MVC框架的异步方法也有很多,这里介绍三种方法: 一.JQuery的Get方法 view @{ Layout = null; } <!DOCTYPE h ...

  3. ajax 使用 三种方法 设置csrf_token的装饰器

    1. CSRF中间件   CSRF跨站请求伪造 2. 补充两个装饰器  from django.views.decorators.csrf import csrf_exempt, csrf_prote ...

  4. javascript实现原生ajax的几种方法介绍

    自从javascript有了各种框架之后,比如jquery,使用ajax已经变的相当简单了.但有时候为了追求简洁,可能项目中不需要加载jquery这种庞大的js插件.但又要使用到ajax这种功能该如何 ...

  5. AJAX实现跨域的三种方法

    由于在工作中需要使用AJAX请求其他域名下的请求,但是会出现拒绝访问的情况,这是因为基于安全的考虑,AJAX只能访问本地的资源,而不能跨域访问. 比如说你的网站域名是aaa.com,想要通过AJAX请 ...

  6. Ajax跨域的几种方法以及每种方法的原理

    js中几种实用的跨域方法原理详解 这里说的js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据.只要协 ...

  7. ajax异步提交的两种方法

    第一种是原始的ajax,第二种是在jQuery中使用ajax.这是我为测试两种提交方法而写的一段代码. 1.struts.xml <package name="json" e ...

  8. ASP.NET MVC 实现AJAX跨域请求的两种方法

    通常发送AJAX请求都是在本域内完成的,也就是向本域内的某个URL发送请求,完成部分页面的刷新.但有的时候需要向其它域发送AJAX请求,完成数据的加载,例如Google. 在ASP.NET MVC 框 ...

  9. struts2实现ajax校验的2种方法

    共同的一点是,Action都需要将一个方法暴露出来,给前端javascript调用  javascript的代码都是一样的: Js代码   function testAjax() { var $use ...

随机推荐

  1. NSCache 的好处

    相较于 NSDictionary 线程安全 系统资源将要耗尽时,自动删减缓存 自动删减"最久未使用的"对象 不会自动拷贝键.因为有些键不支持拷贝操作 可以和 NSPurgeable ...

  2. Class 和 MetaClass

    在 OC 中,类的一个实例定义如下: /// Represents an instance of a class. struct objc_object { Class _Nonnull isa OB ...

  3. Python小白学习之路(四)——第一次练习题

    写在前面: 今天下雪了呢!连着两天都没有更新学习记录. 我没有偷懒呢.做了一天的练习题,昨天学的内容还没总结完,太累了就回去睡觉了 连续一周早起,强大的内心也无法支撑我疲惫的身体 今天早起做了整理.加 ...

  4. C#获取文件版本、文件大小等信息

    使用以下C#程序代码可以非常方便地获取Windows系统中任意一个文件(尤其是可执行文件)的文件版本.文件大小.版权.产品名称等信息.所获取到的信息类似于在Windows操作系统中右键点击该文件,然后 ...

  5. 添加新内容的四个 jQuery 方法:append,prepend,after,before

    添加新内容的四个 jQuery 方法区别如下: append() - 在被选元素(里面)的结尾插入内容prepend() - 在被选元素(里面)的开头插入内容 //jQuery append() 方法 ...

  6. (转) MySQL分区与传统的分库分表

    传统的分库分表 原文:http://blog.csdn.net/kobejayandy/article/details/54799579 传统的分库分表都是通过应用层逻辑实现的,对于数据库层面来说,都 ...

  7. Amazon S3 功能介绍

    一 .Amazon S3介绍 Amazon Simple Storage Service (Amazon S3) 是一种对象存储,它具有简单的 Web 服务接口,可用于在 Web 上的任何位置存储和检 ...

  8. 【Java并发编程】:并发新特性—信号量Semaphore

    在操作系统中,信号量是个很重要的概念,它在控制进程间的协作方面有着非常重要的作用,通过对信号量的不同操作,可以分别实现进程间的互斥与同步.当然它也可以用于多线程的控制,我们完全可以通过使用信号量来自定 ...

  9. PHP 批量获取 百度搜索结果 网址列表

    <?php set_time_limit(0); function curl($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $u ...

  10. 用as3.0制作一个滚动条组件

    本实例演示了实现一个滚动条基本功能的制作方法,没有添加改变皮肤,修改滚动条视框大小等功能,有兴趣的朋友可根据自己要求自行添加.使用时只需要通过以下一行代码创建滚动条组件: var myScrollba ...