在JQuery中,$.ajax() 的用法

1.url:
要求为String类型的参数,(默认为当前页地址)发送请求的地址。
2.type:
要求为String类型的参数,请求方式(post或get)默认为get。注意其他http请求方法,例如put和delete也可以使用,但仅部分浏览器支持。
3.timeout:
要求为Number类型的参数,设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup()方法的全局设置。
4.async:
要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其他操作必须等待请求完成才可以执行。
5.cache:
要求为Boolean类型的参数,默认为true(当dataType为script时,默认为false),设置为false将不会从浏览器缓存中加载请求信息。
6.data:
要求为Object或String类型的参数,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式。get请求中将附加在url后。防止这种自动转换,可以查看  processData选项。对象必须为key/value格式,例如{foo1:"bar1",foo2:"bar2"}转换为&foo1=bar1&foo2=bar2。如果是数组,JQuery将自动为不同值对应同一个名称。例如{foo:["bar1","bar2"]}转换为&foo=bar1&foo=bar2。
7.dataType:
要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。可用的类型如下:
xml:返回XML文档,可用JQuery处理。
html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。
script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求。
json:返回JSON数据。
jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个“?”为正确的函数名,以执行回调函数。
text:返回纯文本字符串。
8.beforeSend:
要求为Function类型的参数,发送请求前可以修改XMLHttpRequest对象的函数,例如添加自定义HTTP头。在beforeSend中如果返回false可以取消本次ajax请求。XMLHttpRequest对象是惟一的参数。
            function(XMLHttpRequest){
               this;   //调用本次ajax请求时传递的options参数
            }
9.complete:
要求为Function类型的参数,请求完成后调用的回调函数(请求成功或失败时均调用)。参数:XMLHttpRequest对象和一个描述成功请求类型的字符串。
          function(XMLHttpRequest, textStatus){
             this;    //调用本次ajax请求时传递的options参数
          }
10.success:要求为Function类型的参数,请求成功后调用的回调函数,有两个参数。
         (1)由服务器返回,并根据dataType参数进行处理后的数据。
         (2)描述状态的字符串。
         function(data, textStatus){
            //data可能是xmlDoc、jsonObj、html、text等等
            this;  //调用本次ajax请求时传递的options参数
         }
11.error:
要求为Function类型的参数,请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错误信息、捕获的错误对象(可选)。ajax事件函数如下:
       function(XMLHttpRequest, textStatus, errorThrown){
          //通常情况下textStatus和errorThrown只有其中一个包含信息
          this;   //调用本次ajax请求时传递的options参数
       }
12.contentType:
要求为String类型的参数,当发送信息至服务器时,内容编码类型默认为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合。
13.dataFilter:
要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。提供data和type两个参数。data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的dataType参数。函数返回的值将由jQuery进一步处理。
            function(data, type){
                //返回处理后的数据
                return data;
            }
14.dataFilter:
要求为Function类型的参数,给Ajax返回的原始数据进行预处理的函数。提供data和type两个参数。data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的dataType参数。函数返回的值将由jQuery进一步处理。
            function(data, type){
                //返回处理后的数据
                return data;
            }
15.global:
要求为Boolean类型的参数,默认为true。表示是否触发全局ajax事件。设置为false将不会触发全局ajax事件,ajaxStart或ajaxStop可用于控制各种ajax事件。
16.ifModified:
要求为Boolean类型的参数,默认为false。仅在服务器数据改变时获取新数据。服务器数据改变判断的依据是Last-Modified头信息。默认值是false,即忽略头信息。
17.jsonp:
要求为String类型的参数,在一个jsonp请求中重写回调函数的名字。该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,例如{jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。
18.username:
要求为String类型的参数,用于响应HTTP访问认证请求的用户名。
19.password:
要求为String类型的参数,用于响应HTTP访问认证请求的密码。
20.processData:
要求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度来讲并非字符串)以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM树信息或者其他不希望转换的信息,请设置为false。
21.scriptCharset:
要求为String类型的参数,只有当请求时dataType为"jsonp"或者"script",并且type是GET时才会用于强制修改字符集(charset)。通常在本地和远程的内容编码不同时使用。
案例代码:
$(function(){     $('#send').click(function(){          $.ajax({              type: "GET",              url: "test.json",              data: {username:$("#username").val(), content:$("#content").val()},              dataType: "json"
,              success: function(data){                          $(
'#resText').empty();
//清空resText里面的所有内容  var
html = ''
;                           $.each(data, function(commentIndex, comment){                                html
+= '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para"' + comment['content'] + '</p></div>';                          });                          $('#resText').html(html);                       }          });     }); });
 
22.顺便说一下$.each()函数:
$.each()函数不同于JQuery对象的each()方法,它是一个全局函数,不操作JQuery对象,而是以一个数组或者对象作为第1个参数,以一个回调函数作为第2个参数。回调函数拥有两个参数:第1个为对象的成员或数组的索引,第2个为对应变量或内容。


$.ajax的一般格式
$.ajax({
     type: 'POST',
     url: url ,
    data: data ,
    success: success ,
    dataType: dataType
});

需要注意的一些地方:
  1.data主要方式有三种,html拼接的,json数组,form表单经serialize()序列化的;通过dataType指定,不指定智能判断。

  2.$.ajax只提交form以文本方式,如果异步提交包含<file>上传是传过不过去,需要使用jquery.form.js的$.ajaxSubmit


$.ajax我的实际应用例子
//1.$.ajax带json数据的异步请求
  var aj = $.ajax( { 
     url:'productManager_reverseUpdate',// 跳转到 action 
      data:{ 
              selRollBack : selRollBack, 
               selOperatorsCode : selOperatorsCode, 
              PROVINCECODE : PROVINCECODE, 
               pass2 : pass2 
     }, 
     type:'post', 
     cache:false, 
    dataType:'json', 
     success:function(data) { 
        if(data.msg =="true" ){ 
             // view("修改成功!"); 
             alert("修改成功!"); 
             window.location.reload(); 
         }else{ 
            view(data.msg); 
        } 
      }, 
     error : function() { 
           // view("异常!"); 
          alert("异常!"); 
      } 
});


//2.$.ajax序列化表格内容为字符串的异步请求
function noTips(){ 
     var formParam = $("#form1").serialize();//序列化表格内容为字符串 
     $.ajax({ 
        type:'post',     
        url:'Notice_noTipsNotice', 
         data:formParam, 
         cache:false, 
         dataType:'json', 
        success:function(data){ 
         } 
     }); 



//3.$.ajax拼接url的异步请求
var yz=$.ajax({ 
      type:'post', 
      url:'validatePwd2_checkPwd2?password2='+password2, 
      data:{}, 
     cache:false, 
     dataType:'json', 
     success:function(data){ 
           if( data.msg =="false" ) //服务器返回false,就将validatePassword2的值改为pwd2Error,这是异步,需要考虑返回时间 
           { 
                textPassword2.html("<font color='red'>业务密码不正确!</font>"); 
                $("#validatePassword2").val("pwd2Error"); 
                checkPassword2 = false; 
                return; 
           } 
       }, 
       error:function(){} 
});


//4.$.ajax拼接data的异步请求
$.ajax({  
     url:'<%=request.getContextPath()%>/kc/kc_checkMerNameUnique.action',  
    type:'post',  
    data:'merName='+values,  
     async : false, //默认为true 异步  
    error:function(){  
       alert('error');  
    },  
    success:function(data){  
        $("#"+divs).html(data);  
       }
});


$.ajax()跟($.post(),$.get())最主要的差别就是 成功回调后,执行success. . $.post(),$.get()就只能简单的做下传递 ,返回. .后续工作没法继续.所以看情况调用
在JQuery中,AJAX有三种实现方式:$.ajax() , $.post , $.get()。
首先我们看$.get():

$.get("test.jsp",
{ name: "cssrain", time: "2008/01/21" }, //要传递的数据
function(data){
alert("返回的数据: " + data);
}
)

然后看$.post():
跟$.get()格式一样.

$.post("test.jsp",
{ name: "cssrain", time: "2008/01/21" }, //要传递的数据
function(data){
alert("返回的数据: " + data);
}
)

上面2种方式的区别应该就是 请求方式不同(一个get 一个post).
最后我们看$.ajax():

$.ajax({
url:'Accept.jsp',
type:'post', //数据发送方式
dataType:'html', //接受数据格式 (这里有很多,常用的有html,xml,js,json)
data:'text='+$("#name").val()+'&date='+new Date(), //要传递的数据
error: function(){ //失败
alert('Error loading document');
},
success: function(msg){ //成功
alert( "Data Saved: " + msg );
}
});

实例
前台jsp部分的代码如下:...
票数:

<span id="i<%=id%>"><%=vote_number%></span><br/>
<a onclick=myvote(<%=id%>); href='javascript:;'">投票</a>

...
js部分的代码如下

function myvote(id){
$.post("vote.jsp", { id: id },
function(data){
eval("var data="+data);
if (data.issucc=="0"){
alert(data.mess)
}else{
//alert("更新页面");
$("#i"+data.myid).html(data.votenum);
}
});
}

返回数据为json
后台返回的json数据如下
{issucc:,mess:”“,votenum:,myid:}
issucc:是否成功
mess:信息,主要是错误信息,比如没登录,超过限制等
votenum:投票后的得票总数
myid:投票的id,用于更新页面的投票数
一个注册登录实例
js
login.jsp返回的类型为text形式,正确时是“OK”,错误时是
“error”。

var userName;
var password;
var result;
$(document).ready(function(){
$("#load").hide();
$("#success").hide();
$("#error").hide();
});
$(document).ready(function(){
$("#button").click(function(){
$("#error").hide();
$("#load").show("slow");
userName = $("#userName").val();
password = $("#password").val();
$.ajax({type: "post",
url: "login.jsp",
dataType: "html",
data: "userName="+userName+"&password="+password,
success: function(result){
var res = String($.trim(result));
if(res=="OK"){
$("#myTable").hide("slow");
$("#success").show("slow");
}else if(res=="error"){
$("#error").show("slow");
$("#load").hide("slow");
}else{
alert("返回异常");}
}
});
});
});

jsp页面
第一种responseText格式

<%@ page language="java" pageEncoding="gb2312"%>
<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if(password.equals("longleg")&&userName.equals("thy")){
out.print("OK");
}else{out.print("error");}
%>


代码中有注释,大家参考使用吧
undefined

$.ajax({
            url: '这个地址要换成你自己的',
            data: {S_CourseID: courseid , CurrTime : new Date().getTime()}, //加个时间戳,否则会不自动更新数据
            dataType: 'json',
            success: function(data)
            {
                if (data != null) {
                    if ( data.length > 0) {
                         for(var i = 0 ; i < data.length ;i++){
specids = specids + data[i].S_SpecialtyID + ","; //获取JSON对象中的数据
coursetypeid = data[i].S_CourseTypeID ;
   }
if(specids.length>0){specids=specids.substring(0,specids.length-1);
                        }
               }


今天有这样一个需求,点击六个大洲,出现对应的一些请求信息,展示在下面,请求请求过后,第二次点击就无需请求。
如图所示:点击北美洲下面出现请求的一些数

html代码结构:
<div class="conSixmap">
  <div class="name conmap01" data-name="beimeizhou">
    <a href="javascript:void(0)">北美洲</a>
    <div class="condetail"></div>
  </div>
  <div class="name conmap02" data-name="nanmeizhou">
    <a href="javascript:void(0)">南美洲</a>
    <div class="condetail"></div>
  </div>
  <div class="name conmap03" data-name="ouzhou">
    <a href="javascript:void(0)">欧洲</a>
    <div class="condetail"></div>
  </div>
  <div class="name conmap04" data-name="feizhou">
    <a href="javascript:void(0)">非洲</a>
    <div class="condetail"></div>
  </div>
  <div class="name conmap05" data-name="yazhou">
    <a href="javascript:void(0)">亚洲</a>
    <div class="condetail"></div>
  </div>
  <div class="name conmap06" data-name="dayangzhou">
    <a href="javascript:void(0)">大洋洲</a>
    <div class="condetail"></div>
  </div>
</div>

css样式:
.conSixmap{position:relative;width:678px;height:335px;margin:0 auto;background:url(../images/tuanduimapBg.png) no-repeat;color:#000;font-family:"微软雅黑"}
.conSixmap .name .condetail{display:none;position:absolute;z-index:10;width:216px;padding:10px;left:50%;margin-left:-118px;top:54px;background:url(../images/opcity83.png) repeat;border-radius:5px;}
.conSixmap .condetail span{display:block;color:#fff;font-size:14px;text-align:left;}
.conSixmap .name{position:absolute;width:52px;height:55px;}
.conSixmap .name a{display:block;z-index:2;position:absolute;padding-top:35px;text-align:center;cursor:pointer;width:52px;height:20px;color:#000;font-size:12px;}
.conSixmap .conmap01{left:91px;top:73px;}
.conSixmap .conmap01 a{background:url(../images/beimeipicBg.png) no-repeat top center;}
.conSixmap .conmap02 {left:180px;top:213px;}
.conSixmap .conmap02 a{background:url(../images/nanmeimapbg.png) no-repeat top center;}
.conSixmap .conmap03 {left:339px;top:68px;}
.conSixmap .conmap03 a{background:url(../images/ouzhoumapBg.png) no-repeat top center;}
.conSixmap .conmap04{left:327px;top:158px;}
.conSixmap .conmap04 a{background:url(../images/feizhoumapbg.png) no-repeat top center;}
.conSixmap .conmap05 {left:480px;top:75px;}
.conSixmap .conmap05 a{background:url(../images/yazhoumapBg.png) no-repeat top center;}
.conSixmap .conmap06 {left:545px;top:220px;}
.conSixmap .conmap06 a{background:url(../images/dayangmapbg.png) no-repeat top center;}
json格式:
{
  "beimeizhou": [
    "请求的json数据1",
    "请求的json数据2"
  ],
  "nanmeizhou": [
    "请求的json数据3",
    "请求的json数据4"
  ],
  "ouzhou": [
    "请求的json数据5",
    "请求的json数据6",
    "请求的json数据7",
    "请求的json数据8"
  ],
  "feizhou": [
    "请求的json数据9",
    "请求的json数据10",
    "请求的json数据11",
    "请求的json数据12"
  ],
  "yazhou": [
    "请求的json数据13",
    "请求的json数据14"
  ],
  "dayangzhou": [
    "请求的json数据15",
    "请求的json数据16"
  ]
}

js代码:
$(document).ready(function(){
  //添加地图
  var stauteArr={
      'beimeizhou':'true',
      'nanmeizhou':'true',
      'ouzhou':'true',
      'feizhou':'true',
      'yazhou':'true',
      'dayangzhou':'true'
    };
  $(".conSixmap .name").on('click',function(){
    var _this=this;
    var htmlcon="";
    $(this).siblings(".name").children(".condetail").fadeOut(500);
    $(this).children(".condetail").fadeIn(500);
    var _name=$(this).attr('data-name');
     $.ajax({
      url:"js/schoolMap.json",
      type:'get',
      data:{},
      dataType:"json",
      success: function(data){
        for(var i in data){
          if(_name==i && stauteArr[i]=='true'){
            for(var j=0;j<data[i].length;j++){
               htmlcon+="<span>"+data[i][j]+"</span>";
            }
            $(_this).children(".condetail").append(htmlcon);
            stauteArr[i]='false';
          }
        }
      },
      error: function(){
        alert('请求失败,请检查网络');
      }
    });
  });
});

猜你喜欢

转载自zhyp29.iteye.com/blog/2293918
今日推荐