Ajax与JSon基础知识

1 ajax

Asynchronous Javascript And XML(异步JavaScript和XML)
    ajax一个技术集合
    dhtml:动态的html  =html+css+js+浏览器内置对象(dom)
    ajax:            =dhtml+XMLHttpRequest对象
功能: 1 局部刷新:通过请求服务器 更改页面的局部局部数据 但不刷新页面
      2 异步提交:在发出一个请求1后 可以在没接收到响应1时  即可发出请求2
使用场景:
     1 百度搜索框的列表
     2 用户名存在提示

2 原生态的ajax的get提交

  • jsp
<div id="div1">div1</div>
<input  type="button" value="原生态ajax的get" onclick="testGet1()"/><br/>
    <script type="text/javascript">
        function testGet1(){
        //1 获取XMLHttpRequest对象
        var xmlRequest=getXMLHttpRequest();
        //2 开启连接
        xmlRequest.open("GET","<c:url value='/AjaxServlet?age=1'/>",true);
        //参数1:请求方式:GET/POST
        //参数2:请求的url
        //参数3:是否异步
        //3 发送请求
        xmlRequest.send();
        //参数:请求时携带的参数-->
        //:::如果是get请求:值为null
        //:::如果是post请求:值格式:age=1&name=hehe
        //4 时刻等待响应 监听事件 
        xmlRequest.onreadystatechange=function(){
            //通过判断readyState变量的值和响应状态码 判断响应的状态
            if(xmlRequest.readyState==4&&xmlRequest.status==200){
                //xmlRequest.readyState=0:对象ActiveXObject初始化完毕
                //xmlRequest.readyState=1:对象ActiveXObject请求连接
                //xmlRequest.readyState=2:对象ActiveXObject连接成功
                //xmlRequest.readyState=3:服务器正在响应
                //xmlRequest.readyState=4:服务器响应完毕
                //获取响应数据
                var data=xmlRequest.responseText;
                $("#div1").html(data.fontcolor("red").bold());
            }
        }


    }
//*** 获取XMLHttpRequest对象 ***
function getXMLHttpRequest(){
    var xmlRequest=null;
    try{
        xmlRequest=new XMLHttpRequest();
    }catch(e){
        try{
            //当前浏览器不支持XMLHttpRequest类型  当前浏览器是ie5/ie6
            xmlRequest=new ActiveXObject("Microsoft.XMLHTTP");
        }catch(e){
            xmlRequest=new ActiveXObject("Msxml2.XMLHTTP");//更老版本的ie
        } 
    }
    return xmlRequest;
}
</script>
  • servlet
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取请求参数
    int age=Integer.parseInt(req.getParameter("age"));
    //告诉客户端用utf-8解码
    resp.setCharacterEncoding("UTF-8");
    //告诉客户端用的是text/html类型,用的是utf-8编码
    resp.setContentType("text/html;charset=utf-8");
    //在客服端打印
    resp.getWriter().print("age="+age);
}

3 原生态的ajax的post提交

  • jsp
<div id="div2">div2</div>
<input  type="button" value="原生态ajax的post" onclick="testGet2()"/><br/>
<script type="text/javascript">
    function testGet2(){
        //1 获取XMLHttpRequest对象
        var xmlRequest=getXMLHttpRequest();
        //2 开启连接
        //区别1:请求方式::POST
        xmlRequest.open("POST","<c:url value='/AjaxServlet'/>",true);
        //3 发送请求
        //区别2:设置请求头:Content-Type   模拟表单提交
        xmlRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        //区别3:send的参数列表是请求参数
        xmlRequest.send("age=2&name=张三");
        //4 时刻等待响应 监听事件
        xmlRequest.onreadystatechange=function(){
            //通过判断readyState变量的值和响应状态码 判断响应的状态
            if(xmlRequest.readyState==4&&xmlRequest.status==200){
                //xmlRequest.readyState=0:对象ActiveXObject初始化完毕
                //xmlRequest.readyState=1:对象ActiveXObject请求连接
                //xmlRequest.readyState=2:对象ActiveXObject连接成功
                //xmlRequest.readyState=3:服务器正在响应
                //xmlRequest.readyState=4:服务器响应完毕
                //获取响应数据
                var data=xmlRequest.responseText;
                $("#div2").html(data.fontcolor("red").bold());
            }
        }


    }
</script>
  • servlet
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取请求参数
    int age=Integer.parseInt(req.getParameter("age"));
    String name=req.getParameter("name");
    //告诉客户端用utf-8解码
    resp.setCharacterEncoding("UTF-8");
    //告诉客户端用的是text/html类型,用的是utf-8编码
    resp.setContentType("text/html;charset=utf-8");
    //在客服端打印
    resp.getWriter().print("age="+age+":::name="+name);
}

4 实现省市级联查询

数据库

CREATE TABLE tab_province(
   pid INT PRIMARY KEY AUTO_INCREMENT,
   pname VARCHAR(11) UNIQUE
);
CREATE TABLE tab_city(
   cid INT PRIMARY KEY AUTO_INCREMENT,
   cname VARCHAR(11) UNIQUE,
   pid INT,
   CONSTRAINT fk_111 FOREIGN KEY(pid) REFERENCES tab_province(pid)
);
INSERT INTO tab_province VALUES(1,"河南");
INSERT INTO tab_province VALUES(2,"北京");
INSERT INTO tab_province VALUES(3,"天津");
INSERT INTO tab_province VALUES(4,"云南");
INSERT INTO tab_province VALUES(5,"河北");
INSERT INTO tab_city VALUES(1000,"郑州",1),(NULL,"汝州",1),(NULL,"濮阳",1),(NULL,"洛阳",1),(NULL,"信阳",1),(NULL,"南阳",1);
INSERT INTO tab_city VALUES(2000,"朝阳区",2),(NULL,"海淀区",2),(NULL,"昌平区",2),(NULL,"通州区",2),(NULL,"顺义区",2),(NULL,"丰台区",2);
INSERT INTO tab_city VALUES(3000,"塘沽区",3),(NULL,"东丽区",3),(NULL,"西青区",3),(NULL,"静海区",3),(NULL,"红桥区",3),(NULL,"武清区",3);
INSERT INTO tab_city VALUES(4000,"昆明",4),(NULL,"大理",4),(NULL,"丽江",4),(NULL,"西双版纳",4),(NULL,"香格里拉",4),(NULL,"玉溪",4);
INSERT INTO tab_city VALUES(5000,"石家庄",5),(NULL,"廊坊",5),(NULL,"白洋淀",5),(NULL,"衡水",5),(NULL,"保定",5),(NULL,"唐山",5);

创建实体类

public class City  implements Serializable{
	private Integer cid;
	private String  cname;
	private Integer pid;
    ...
}
public class Province  implements Serializable{
	private Integer pid;
	private String pname;
	...
}

创建dao

package com.zhiyou100.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.stylesheets.LinkStyle;
import com.zhiyou100.entity.City;
import com.zhiyou100.entity.Province;
import com.zhiyou100.util.JdbcUtil;
public class CityDao {
    public List<City>  getAllByPid(int pid){
        //获取链接
        Connection con=JdbcUtil.getCon();
        //准备sql模板
        String sql="select * from tab_city where pid=?";
        //获取预编译对象
        PreparedStatement pre=null;
        ResultSet set=null;
        List<City> list=new ArrayList<City>();
        try {
            pre=con.prepareStatement(sql);  
            pre.setInt(1, pid);
            set=pre.executeQuery();
            while(set.next()){
                City c=new City();
                c.setCid(set.getInt("cid"));
                c.setPid(set.getInt("pid"));
                c.setCname(set.getString("cname"));
                list.add(c);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally{
            JdbcUtil.release(set, pre, con);
        }
        return list;
    }
}
package com.zhiyou100.dao;
...
public class ProvinceDao {
	  public List<Province>  getAll(){
		  //获取链接
			Connection con=JdbcUtil.getCon();
			//准备sql模板
			String sql="select * from tab_province";
			//获取预编译对象
			PreparedStatement pre=null;
			ResultSet set=null;
			List<Province> list=new ArrayList<Province>();
			try {
			   pre=con.prepareStatement(sql);  
			   set=pre.executeQuery();
			   while(set.next()){
				   Province p=new Province();
				   p.setPid(set.getInt("pid"));
				   p.setPname(set.getString("pname"));
				  list.add(p);
			   }
			} catch (Exception e) {
				throw new RuntimeException(e);
			}finally{
				JdbcUtil.release(set, pre, con);
			}
			return list;

	  }
	  public Province  getOneByPname(String pname){
		  //获取链接
			Connection con=JdbcUtil.getCon();
			//准备sql模板
			String sql="select * from tab_province where pname=?";
			//获取预编译对象
			PreparedStatement pre=null;
			ResultSet set=null;
			Province p=null;
			try {
			   pre=con.prepareStatement(sql);  
			   pre.setString(1, pname);
			   set=pre.executeQuery();
			   if(set.next()){
				   p=new Province();
				   p.setPid(set.getInt("pid"));
				   p.setPname(set.getString("pname"));
			   }
			} catch (Exception e) {
				throw new RuntimeException(e);
			}finally{
				JdbcUtil.release(set, pre, con);
			}
			return p;
	  }
}

对ajax进行封装

// *** 对ajax请求的封装 ***
function myAjaxFunction(method, url, data, fn) {
	// 1.获取XMLHttpRequest对象
	var xmlRequest = null;
	try {
		xmlRequest = new XMLHttpRequset();
	} catch (e) {
		try {
			// 当前浏览器不支持XMLHttpRequest类型 当前浏览器是ie5/ie6
			xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
			// 更老版本的ie浏览器
			xmlRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
	}

	// 开启连接
	xmlRequest.open(method, url, true);
	if (method == "POST" || method == "post") {
		// 2.设置请求头:Content-Type
		xmlRequest.setRequestHeader("Content-Type",
				"application/x-www-form-urlencoded");
	}

	// 3.发送请求
	xmlRequest.send(data);
	// 4.时刻等待响应,监听事件
	xmlRequest.onreadystatechange = function() {
		// 通过判断readyState变量的值和响应状态码 判断响应的状态
		if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
			// 获取响应数据
			var data = xmlRequest.responseText;
			fn(data);
		}
	}
}

页面

请选择你的地址:
<select name="province">
    <option>请选择省份</option>
</select>
<select name="city">
    <option>请选择城市</option>
</select><br/>

<script type="text/javascript">
    $(function(){
        //页面打开  通过ajax获取所有的省份  并拼凑option、添加到第一个select中
        myAjaxFunction("GET","<c:url value='/AjaxGetProvinceServlet'/>",null,function(data){
            //使用-切割字符串
            var provinceArr=data.split("-");
            for(var i=0;i<provinceArr.length;i++){
                $("select[name='province']").append($("<option value='"+provinceArr[i]+"'>"+provinceArr[i]+"</option>"));    			  
            }
        });

        //给select name="province"添加onchange事件
        $("select[name='province']").bind("change",function(){
            if($("select[name='province']").val()){
                //获取省份的名字
                var pname=$("select[name='province']").val();
                $("select[name='city'] option:gt(0)").remove();
                //通过ajax获取当前省份对应的城市 并写入第二个select中
                myAjaxFunction("POST","<c:url value='/ajax/getCity'/>","pname="+pname,function(data){
                    //使用-切割字符串
                    var cityArr=data.split("-");
                    for(var i=0;i<cityArr.length;i++){
                        $("select[name='city']").append($("<option value='"+cityArr[i]+"'>"+cityArr[i]+"</option>"));    			  
                    }
                });

            }
        });
    });
</script>

servlet:/ajax/getProvince

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    List<Province> list=new ProvinceDao().getAll();
    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html;charset=utf-8");
    String message="";
    for (Province province : list) {
        message+="-";
        message+=province.getPname();

    }
    message=message.substring(1);
    resp.getWriter().print(message);

}

servlet:/ajax/getCity

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    String pname=req.getParameter("pname");
    System.out.println("pname="+pname);
    //根据pname获取province
    Province province=new ProvinceDao().getOneByPname(pname);
    //根据pid获取city的list
    List<City> list=new CityDao().getAllByPid(province.getPid());
    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html;charset=utf-8");
    String message="";
    for (City c : list) {
        message+="-";
        message+=c.getCname();

    }
    message=message.substring(1);
    resp.getWriter().print(message);
}

5 json

JSON: 是一种轻量级的数据交换格式,主要用于传送数据
	  JSON可以将js对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串
可以被js直接解析的一种数据结构
json数据---json对象
json对象---类似于java中对象(封装数据)
格式:{属性名:性值,属性名:属性值,...}
注意:1 json属性值类型:数字+boolean+字符串+json对象+数组+null
     2 属性名必须写在双引号中

案例1

<input  type="button" value="测试json" onclick="testGet1()"/><br/>
<script type="text/javascript">
    function testGet1(){
        //把字符串转换为json对象
        var json1={"name":"韩梅梅","age":18,"score":19.5,"dy":true,
                   "enjoy":["篮球","排球","足球"],"wife":null,"friend":{"fname":"张三","fage":11}};
        	alert("json1="+json1);//json1=[object Object]
       		alert(json1.name+":::"+json1.age+":::"+json1.score+":::"+
        	      json1.dy+":::"+json1.enjoy+":::"+json1.wife+"::::"+json1.friend.fname);
        		  //韩梅梅:::18:::19.5:::true:::篮球,排球,足球:::null::::张三
		//把字符串转换为json对象
        var json2=[{"name":"韩梅梅","age":11},{"name":"韩庚","age":12},{"name":"韩信","age":13}];
        alert(json2+":::"+json2.length+":::"+json2[0].name);
        //[object Object],[object Object],[object Object]:::3:::韩梅梅
    }
</script>

eval方法的使用

作用:把字符串参数解析成JS代码并运行,并返回执行的结果;
<input  type="button" value="测试global对象的方法eval" onclick="testGet4()"/><br/>
<script type="text/javascript">
    function testGet4(){
        var data="alert(11);";
        //对字符串中的字符进行解析:通过js的global对象的eval
        //把字符串参数解析成JS代码并运行,并返回执行的结果;
        eval(data);//弹出框,弹出一个11
    }
</script>

java响应json格式的字符串

  • 页面
<input  type="button" value="获取一个学生" onclick="testGet2()"/><br/>
<script type="text/javascript">
    //js与java通信 通过ajax
    function testGet2(){
        myAjaxFunction("GET","<c:url value='/JsonTextServlet?n=1'/>",null,function(data){
            //得到的是json对象的字符串
            //json对象:{}
            //json对象的字符串:"{}"

            //通过global的eval解析字符串 可以得到json对象
            //{ "sid":1267,"sname":"韩梅梅","score":65.6,"sdy":true,"enjoys":["篮球","足球","排球","铅球"] }
            alert(data);
            //data解析后不是语句  是一个数据  要加()解析
            var dataJson=eval("("+data+")");
            alert(dataJson+":::"+dataJson.sname);//[object Object]:::韩梅梅
        });
    }
</script>

<input  type="button" value="获取所有学生" onclick="testGet3()"/><br/>
<script type="text/javascript">
    //js与java通信 通过ajax
    function testGet3(){
        myAjaxFunction("GET","<c:url value='/JsonTextServlet?n=2'/>",null,function(data){
            alert(data);
            var arr=eval("("+data+")");
            //[object Object],[object Object],[object Object],[object Object]::4::韩梅梅
            alert(arr+"::"+arr.length+"::"+arr[0].sname);
        });
    }
</script>
  • servlet :/JsonTextServlet
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    int n=Integer.parseInt(req.getParameter("n"));
    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html;charset=utf-8");
    if(n==1){
        Student s=new Student((int)(Math.random()*1000+1000), 
                              "韩梅梅",
                              (int)(Math.random()*1000)/10.0f, 
                              Math.random()>0.5, 
                              new String[]{"篮球","足球","排球","铅球"});
        //java不识别json对象
        //只能通过java拼凑一个json格式的字符串	
        String data=student2Json(s);
        resp.getWriter().print(data);
        return;
    }
    //创建多个student对象 装入集合
    List<Student> list=new ArrayList<Student>();
    list.add(new Student((int)(Math.random()*1000+1000), 
                         "韩梅梅",
                         (int)(Math.random()*1000)/10.0f, 
                         Math.random()>0.5, 
                         new String[]{"篮球","足球","排球","铅球"})); 
    list.add(new Student((int)(Math.random()*1000+1000), 
                         "韩庚",
                         (int)(Math.random()*1000)/10.0f, 
                         Math.random()>0.5, 
                         new String[]{"语文","英语","历史","铅球"}));
    list.add(new Student((int)(Math.random()*1000+1000), 
                         "韩信",
                         (int)(Math.random()*1000)/10.0f, 
                         Math.random()>0.5, 
                         new String[]{"打架","斗殴","钓鱼","武术"}));
    list.add(new Student((int)(Math.random()*1000+1000), 
                         "韩非子",
                         (int)(Math.random()*1000)/10.0f, 
                         Math.random()>0.5, 
                         new String[]{"篮球","足球","排球","铅球"}));
    //把list封装为js中的数组对应的字符串  数组中装的是json
    String data="[ ";
    for (Student s : list) {
        String jsonS=student2Json(s);
        data+=jsonS+",";
    }
    data=data.substring(0,data.length()-1);
    data+="]";
    resp.getWriter().print(data);

}
//获取一个Student对象对应的json
private static String student2Json(Student s){
    StringBuilder  stb=new StringBuilder();
    stb.append("{ ");
    stb.append("\"sid\":"+s.getSid());
    stb.append(",");
    stb.append("\"sname\":\""+s.getSname()+"\"");
    stb.append(",");
    stb.append("\"score\":"+s.getScore());
    stb.append(",");
    stb.append("\"sdy\":"+s.isSdy());
    stb.append(",");
    stb.append("\"enjoys\":"+getStr(s.getEnjoys()));
    stb.append(" }");
    return stb.toString();
}
//获取一个String数组对应的字符串
public static String getStr(String[] enjoys){
    String s="[";
    for (String enjoy : enjoys) {
        s+="\""+enjoy+"\"";
        s+=",";
    }
    s=s.substring(0,s.length()-1);
    s+="]";
    return s;
}

使用json的jar实现json格式的字符串

  • 页面
<input  type="button" value="测试json的jar获取一个" onclick="testGet1()"/><br/>
<script type="text/javascript">
    function testGet1(){
        myAjaxFunction("GET","<c:url value='/json/test03?n=1'/>",null,function(data){
            alert(data);
            var dataJson=eval("("+data+")");
            //韩梅梅::79.8:::篮球,足球,排球,铅球
            alert(dataJson.sname+"::"+dataJson.score+":::"+dataJson.enjoys);
        });
    }
</script>
<input  type="button" value="测试json的jar获取多个" onclick="testGet2()"/><br/>
<script type="text/javascript">
    function testGet2(){
        myAjaxFunction("GET","<c:url value='/json/test03?n=2'/>",null,function(data){
            alert(data);
            var dataJsonArr=eval("("+data+")");
            //[object Object],[object Object],[object Object],[object Object]:::4::韩梅梅:::篮球,足球,排球,铅球
            alert(dataJsonArr+":::"+dataJsonArr.length+"::"
                  +dataJsonArr[0].sname+":::"+dataJsonArr[0].enjoys);
        });
    }
</script>
  • 移入jar
commons-beanutils-1.8.3.jar
commons-collections-3.2.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
xom-1.1.jar
  • servlet:/json/test03
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    int n=Integer.parseInt(req.getParameter("n"));
    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html;charset=utf-8");
    if(n==1){
        Student s=new Student((int)(Math.random()*1000+1000), 
                              "韩梅梅",
                              (int)(Math.random()*1000)/10.0f, 
                              Math.random()>0.5, 
                              new String[]{"篮球","足球","排球","铅球"});
        //java不识别json对象
        //只能通过java拼凑一个json格式的字符串	
        JSONObject jo=JSONObject.fromObject(s);//把普通java对象转换为json对象
        String data=jo.toString();//获取json格式的字符串
        System.out.println("data="+data);
        resp.getWriter().print(data);
        return;
    }
    //创建多个student对象 装入集合
    List<Student> list=new ArrayList<Student>();
    list.add(new Student((int)(Math.random()*1000+1000), 
                         "韩梅梅",
                         (int)(Math.random()*1000)/10.0f, 
                         Math.random()>0.5, 
                         new String[]{"篮球","足球","排球","铅球"})); 
    list.add(new Student((int)(Math.random()*1000+1000), 
                         "韩庚",
                         (int)(Math.random()*1000)/10.0f, 
                         Math.random()>0.5, 
                         new String[]{"语文","英语","历史","铅球"}));
    list.add(new Student((int)(Math.random()*1000+1000), 
                         "韩信",
                         (int)(Math.random()*1000)/10.0f, 
                         Math.random()>0.5, 
                         new String[]{"打架","斗殴","钓鱼","武术"}));
    list.add(new Student((int)(Math.random()*1000+1000), 
                         "韩非子",
                         (int)(Math.random()*1000)/10.0f, 
                         Math.random()>0.5, 
                         new String[]{"篮球","足球","排球","铅球"}));
    //把list封装为js中的数组对应的字符串  数组中装的是json
    JSONArray ja=JSONArray.fromObject(list);
    String data=ja.toString();
    System.out.println("data="+data);
    resp.getWriter().print(data);
}

6 jquery中执行ajax

jquery中执行ajax相关的三个方法

      jquery中实现ajax的方法
       1:$.ajax([options])
               参数1:async : 是否异步 默认true
               参数2:cache: 是否使用缓存
		       参数3:data:请求参数
		       参数4:dataType:期待服务器响应数据的类型:text html json
		       参数5:error:错误的回调函数
		       参数6:success:成功后的回调函数
		       参数7:type:请求方式:GET默认/POST
		       参数8:url:请求的资源的路径  
	  2:$.get(url, [data], [callback], [type]) 
	  3:$.post(url, [data], [callback], [type])   
	        url:请求资源的路径
	        data:请求参数
	        callback:成功的回调函数
	        type:期待服务器的响应数据的类型  

servlet:AgaxTextServlet

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("请求方式:::"+req.getMethod());   
    int n=Integer.parseInt(req.getParameter("n"));
    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html;charset=utf-8");
    if(n==1){//响应字符串
        resp.getWriter().print("doget::::jquery的ajax你好!");
        return;
    }
    if(n==2){//响应json格式的字符串
        Student s = new Student(
            (int) (Math.random() * 1000 + 1000), "韩梅梅", 
            (int) (Math.random() * 1000) / 10.0f,
            Math.random() > 0.5, new String[] { "篮球", "足球", "排球", "铅球" });
		//把对象s变为字符串
        resp.getWriter().print(JSONObject.fromObject(s).toString());
        return;
    }
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
}

$.ajax方法

<input  type="button" value="测试jquery的ajax方法:响应的是字符串" onclick="testAjax1()"/><br/>
<script type="text/javascript">
    function testAjax1(){
        $.ajax({
            "type":"GET",
            "url":"<c:url value='/AgaxTextServlet'/>",
            "data":"n=1",
            "async":true,
            "cache":false,
            "dataType":"text",
            "success":function(data){
                //doget::::jquery的ajax你好!
                alert(data);
            }
        });
    }
</script>
<input  type="button" value="测试jquery的ajax方法get提交:响应的是json串" onclick="testAjax2()"/><br/>
<script type="text/javascript">
    function testAjax2(){
        $.ajax({
            type:"GET",
            url:"<c:url value='/AgaxTextServlet'/>",
            data:"n=2",
            async:true,
            cache:false,
            dataType:"json",
            success:function(data){
                //[object Object]:::韩梅梅
                alert(data+":::"+data.sname);
            }
        });
    }
</script>

<input  type="button" value="测试jquery的ajax方法post提交:响应的是json串" onclick="testAjax3()"/><br/>
<script type="text/javascript">
    function testAjax3(){
        $.ajax({
            type:"POST",
            url:"<c:url value='/AgaxTextServlet'/>",
            data:"n=2",
            async:true,
            cache:false,
            dataType:"json",
            success:function(data){
                //[object Object]:::韩梅梅
                alert(data+":::"+data.sname);
            }
        });
    }
</script>

$.get方法

<input  type="button" value="测试jquery的get方法:响应字符串" onclick="testGet4()"/><br/>
<script type="text/javascript">
    function testGet4(){
        $.get("<c:url value='/AgaxTextServlet'/>","n=1",function(data){
            //doget::::jquery的ajax你好!
            alert(data);
        },"text");
    }
</script>
<input  type="button" value="测试jquery的get方法:响应json" onclick="testGet5()"/><br/>
<script type="text/javascript">
    function testGet5(){
        $.get("<c:url value='/AgaxTextServlet'/>","n=2",function(data){
            //[object Object]:韩梅梅
            alert(data+":"+data.sname);
        },"json");
    }
</script>

$.post方法

<input  type="button" value="测试jquery的post方法:响应字符串" onclick="testPost6()"/><br/>
<script type="text/javascript">
    function testPost6(){
        $.post("<c:url value='/AgaxTextServlet'/>","n=1",function(data){
            //doget::::jquery的ajax你好!
            alert(data);
        },"text");
    }
</script>
<input  type="button" value="测试jquery的post方法:响应json" onclick="testPost7()"/><br/>
<script type="text/javascript">
    function testPost7(){
        $.post("<c:url value='/AgaxTextServlet'/>","n=2",function(data){
            //[object Object]:韩梅梅
            alert(data+":"+data.sname);
        },"json");
    }
</script>
posted @ 2021-10-21 22:59  RenVei  阅读(44)  评论(0编辑  收藏  举报