Jquery的$.ajax()函数$.get(),$.post(),$.getjson(),$.ajax()

一,$.get(url,[data],[callback])

说明:url为请求地址,data为请求数据的列表(是可选的,也可以将要传的参数写在url里面),callback为请求成功后的回调函数,该函数接受两个参数,第一个为服务器返回的数据,第二个参数为服务器的状态,是可选参数。而其中,服务器返回数据的格式其实是字符串形势,并不是我们想要的json数据格式,在此引用只是为了对比说明。

1 $.get("data.php",$("#firstName.val()"),function(data){
2 
3   $("#getResponse").html(data); }//返回的data是字符串类型
4 
5 );

二,$.post(url,[data],[callback],[type])

说明:这个函数跟$.get()参数差不多,多了一个type参数,type为返回的数据类型,可以是html,xml,json等类型,如果我们设置这个参数为:json,那么返回的格式则是json格式的,如果没有设置,就 和$.get()返回的格式一样,都是字符串的。

复制代码
1 $.post("emp.do?p=getAllEmp",{id:deptId,x:Math.random()},function(data){
2             var arry = eval("("+data+")");//去引号,将json字符串去引号编程json类型数组,也可以在$.post函数后面加一个参数"json",指定接收的数据为json类型的
3             for(var i=0;i<arry.length;i++){
4                 var op = new Option(arry[i].empName,arry[i].empId);
5                 document.getElementById("emp").options.add(op);
6             }
7         });
复制代码

也可以写成下面这样,返回的就是json类型数组了,就不要难过去引号了,可以直接遍历。

1 $.post("emp.do?p=getAllEmp",{id:deptId,x:Math.random()},function(arry){
2             for(var i=0;i<arry.length;i++){
3                 var op = new Option(arry[i].empName,arry[i].empId);
4                 document.getElementById("emp").options.add(op);
5             }
6         },"json");

三,$.ajax(opiton)

说明:$.ajax()这个函数功能强大,可以对ajax进行许多精确的控制,需要详细说明的请参照相关资料

复制代码
1 $.ajax({
2   url: "ajax/ajax_selectPicType.jsp",
3   data:{Full:"fu"},
4   type: "POST",
5   dataType:'json',
6   success:CallBack,
7   error:function(er){
8   BackErr(er);}
9 });
复制代码

四,$.getJSON(url,[data],[callback])

说明:$.getJSON(url,[data],[callback])函数没有type参数,返回的是json类型的,不需要转换。

1 $.getJSON("dep.do?p=getAllDep",{x:Math.random()},function(arry){
2             for(var i=0;i<arry.length;i++){
3                 var op = new Option(arry[i].deptName,arry[i].deptId);
4                 document.getElementById("dep").options.add(op);
5             }
6         });
原文地址:https://www.cnblogs.com/fengsantianya/p/5891888.html