jQuery是一個輕量級js框架,使用方便快捷,更是封裝ajax處理方法,如$.load() $.get() $.post() 等javascript
但最經常使用的方法仍是$.ajax()css
1、通常的格式爲html
$.ajax({ type: 'POST', async: false, //注意這裏要求爲Boolean類型的參數,false不能寫成'false'否則會被解析成true url: url , data: data , dataType:'json', cache:false, //同理 success: success , error:error, dataType: dataType });
一、type(發送方式 post與get的區別 )java
不一樣點一:get提交方式會把請求參數以key,value的方式拼接到url中,以致於對提交數據大小有所限制,最長2048個字符;post提交方式是經過HTT請求附件進行,能夠實現大量數據傳送,在url上不會顯示數據,而是保存在web服務器日誌中。因此相對而言post提交方式對數據的安全性獲得支持。jquery
不一樣點二:get提交方式會將數據緩存,而post不會。git
不一樣點三:編碼方式不一樣,具體參照連接,詳細講解了get和post方法處理亂碼問題。 http://www.cnblogs.com/dyllove98/archive/2013/07/31/3228485.htmlweb
若是使用get方法提交,在後臺獲取值的時候必須使用new String(className.getBytes("ISO8859-1"),"UTF-8")來進行轉碼才能夠不亂碼
若是使用post方式提交,在後臺不亂碼,前提是在web.xml已經配置了編碼過濾器,而且在頁面中也配置了相應的編碼格式
二、async (同步方式 true和false的區別)ajax
async默認的設置值爲true,這種狀況爲異步方式,就是說當ajax發送請求後,在等待server端返回的這個過程當中,前臺會繼續 執行ajax塊後面的腳本,直到server端返回正確的結果纔會去執行success,也就是說這時候執行的是兩個線程,ajax塊發出請求後一個線程 和ajax塊後面的腳本(另外一個線程),設置async值爲false時候,頁面進入阻塞模式並出現假死狀態,直到這個AJAX執行完畢後纔會繼續運行其餘代碼頁面假死狀態解除。數據庫
同步例子如:在一個Bootstrap的popover()運用中動態加載用戶消息時details_in_popup()函數返回參數顯示在pop框中,若不設置async爲同步最終取不到客戶端返回的count值時就返回content值json
<script type="text/javascript"> $('.top-menu #messages').popover({ html:true, placement: 'bottom', content: function(){ var div_id = "tmp-id-" + $.now(); return details_in_popup(div_id); } }); function details_in_popup(div_id){ var uid = $("#uid").text(); var urls = "ajaxMessageCounts.action?identify=1&id=" + uid; var contents = function load_val2(){ var result=''; $.ajax({ dataType:'json', url : urls, async:false,//這裏選擇異步爲false,直到這個AJAX執行完畢後纔會繼續運行其餘代碼 success : function(data){ var count=data.counts; $("#messages").attr('data-notification', count); if(count == '0'){ result = '<ul><li><br></br><center>暫時沒有新消息</center><br></br></li></ul><div class="popover_footer"><a href="searchMessage.action?identify=1&&id='+uid+'&&point=1" target="content">查看所有消息</a></div>'; }else{ var head1=data.head1; var poTime1=data.poTime1; var mid1 = data.mid1; var poName1=data.poName1; var content1=data.content1; if(count == '1'){ result = '<ul><li><a href="showDetail.action?id='+mid1+'&&identify=1&&uid='+uid+'&&point=1" target="content"><img src="backstage/assets/img/gallery/'+head1+'.jpg"><span>'+poTime1+'</span><h4>'+poName1+'</h4>'+content1+'</a></li><ul><div class="popover_footer"><a href="searchMessage.action?identify=1&&id='+uid+'&&point=1" target="content">查看所有消息</a></div>'; } if(count == '2'){ var head2=data.head2; var poTime2=data.poTime2; var mid2 = data.mid2; var poName2=data.poName2; var content2=data.content2; result = '<ul><li><a href="showDetail.action?id='+mid2+'&&identify=1&&uid='+uid+'&&point=1" target="content"><img src="backstage/assets/img/gallery/'+head1+'.jpg"><span>'+poTime1+'</span><h4>'+poName1+'</h4>'+content1+'</a></li><li><a href="#"><img src="backstage/assets/img/gallery/'+head2+'.jpg"><span>'+poTime2+'</span><h4>'+poName2+'</h4>'+content2+'</a></li></ul><div class="popover_footer"><a href="searchMessage.action?identify=1&&id='+uid+'&&point=1" target="content">查看所有消息</a></div>'; } } } }); return result; }; // alert(contents); return contents; } </script>
異步例子如:從用戶體驗度來思考,加載數據時候提示「loading、、、」
$.ajax(function(){ //省略了一些參數,這裏只給出async 和 beforeSend async: true, //同步請求,默認狀況下是異步(true),若寫false將看不到提示內容 beforeSend: function(){ $('#warning').text('loading。。。'); } });
三、url
url是發送請求的連接地址,能夠在URL上拼接請求參數,則提交方式爲get如:
var urls = "ajaxMessageCounts.action?identify=1&id=" + uid;
四、data
data能夠有幾種方式向服務器端發送請求參數:
function details_in_popup(){ $.ajax({ type:'post', url:'ajaxMessageCounts.action', data:'identity='+identity + 'flag='+flag, //文本方式 cache:false, dataType:'json', success:function(data){ } }); }
function details_in_popup(){ $.ajax({ type:'post', url:'ajaxMessageCounts.action', data:{ identity:'123', flag:'true' }, //json對象 cache:false, dataType:'json', success:function(data){ } }); }
function details_in_popup(){ var formParam = $("#form1").serialize();//序列化表單內容爲字符串 $.ajax({ type:'post', url:'ajaxMessageCounts.action', data:formParam, cache:false, dataType:'json', success:function(data){ } }); }
五、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:返回純文本字符串。
六、cache
要求爲Boolean類型的參數,默認爲true(當dataType爲script時,默認爲false),設置爲false將不會從瀏覽器緩存中加載請求信息。
這裏介紹幾種防止緩存的方法:
1)在客戶端請求連接上添加隨機參數:
var url1 = "ajaxMessageCounts.action?date=" + new Date().getTime(); var url2 = "ajaxMessageCounts.action?random=" + Math.random();
2)在HTTP headers禁止緩存:
<!--HTTP--> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="Cache-Control" content="no-cache, must-revalidate" /> <meta http-equiv="expires" content="Thu, 01 Jan 1970 00:00:01 GMT" /> <meta http-equiv="expires" content="0" /> <!--JSP--> response.addHeader("Cache-Control", "no-cache"); response.addHeader("Expires", "Thu, 01 Jan 1970 00:00:01 GMT");
3)在XMLHttpRequest發送請求以前加上:
XMLHttpRequest.setRequestHeader("If-Modified-Since","0"); XMLHttpRequest.send(null);
七、success
要求爲Function類型的參數,請求成功後調用的回調函數,有兩個參數。
(1)由服務器返回,並根據dataType參數進行處理後的數據。
(2)描述狀態的字符串。
function(data, textStatus){ //data多是xmlDoc、jsonObj、html、text等等 this; //調用本次ajax請求時傳遞的options參數 }
八、error
要求爲Function類型的參數,請求失敗時被調用的函數。該函數有3個參數,即XMLHttpRequest對象、錯誤信息、捕獲的錯誤對象(可選)。ajax事件函數以下:
function(XMLHttpRequest, textStatus, errorThrown){ //一般狀況下textStatus和errorThrown只有其中一個包含信息 this; //調用本次ajax請求時傳遞的options參數 }
固然$.ajax()方法參數不止這些,更多參數詳情參考http://www.cnblogs.com/tylerdonet/p/3520862.html。
給個異步加載下拉列表的例子:
<script type="text/javascript"> setJsonSelectValue("problemType","ajaxMessageCounts.action","",{"identify":1}); //selectId:select選擇框ID URL:請求Action value:設置select的selected屬性 param:請求參數,這裏爲json串
function setJsonSelectValue(selectId,url,value,param){ $.ajax({ url: url, cache:false, data:param, async:false, dataType:"json", success: function(data, textStatus, jqXHR){ var select = $("#" + selectId); for(var i=0;i<data.length;i++){ select.options.add(new Option(data[i].name,data[i].value)); //添加option 後臺返回data爲List對象數組 } //設置selected if(value!=""){ var flag = false; $("#"+selectId +" option").each(function() { if (value == $(this).val()) { flag = true; } }); if(flag){ select.value=value; } else{ var first = $("#"+selectId+" option[index='0']").val(); $("#"+selectId).val(first); } } }, error:function (data, textStatus, jqXHR){ alert(textStatus); } }); } </script>
2、ajax與Struts的聯合使用加載對象
一、給出一個後臺封裝json字符串的轉換框架工具Jackson,Jackson能夠輕鬆的將Java對象轉換成json對象和xml文檔,一樣也能夠將json、xml轉換成Java對象。
二、官網下載Jackson工具包,下載地址;現給出總共的封裝Jackson的jar包jackson-all-1.6.4.jar
三、Action代碼:
public class IdentityMessage extends ActionSupport { private int id; private MessageService messagedao; //數據訪問層的組件 public int getId() { return id; } public void setId(int id) { this.id = id; } public MessageService getMessagedao() { return messagedao; } public void setMessagedao(MessageService messagedao) { this.messagedao = messagedao; } public String searchMessage() throws JsonGenerationException, JsonMappingException, IOException{ Message message = messagedao.searchMessage(id);
//前臺主要取title和content屬性 ObjectMapper mapper = new ObjectMapper(); String jsonstr = mapper.writeValueAsString(message); response.setContentType("text/javascript"); response.setCharacterEncoding("utf-8"); response.getWriter().print(jsonstr); return null; } }
四、struts.xml文件配置:
<action name="searchMessage" class="identifyMessBean" method="searchMessage"> </action>
五、applicationContext-beans.xml文件配置:
<bean id="MessageDao" class="com.dao.MessageDao"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="MessageService" class="com.service.MessageService"> <property name="messagedao" ref="MessageDao"/> </bean> <bean id="identifyMessBean" class="com.action.IdentityMessage"> <property name="messagedao" ref="MessageService"/> </bean>
六、jQuery代碼
<script type="text/javascript"> function saveUserMessage(id){ $.ajax({ dataType:'json', url:'searchMessage.action', data: { id: id }, type:'POST', success:function(data){ if(title == ''){ $('#userClose'+id).empty().append("<h5>"+ data.title +"</h5>").append("<div id='contents"+id+"'>"+data.content+"</div>"); }else{ $('#userClose'+id+' h5').text(data.title); $('#contents'+id).html(data.content); } //設置保存成功提示modal $('#example_modaleditUser').modal('hide'); $("#example_modal3").css({position: "absolute", right: "600px", top: "20px",display:"block"}).width(170).height(20).show(3000); $('#example_modal3').delay(1500).hide(0); }, error:function(){ //設置保存失敗提示modal $('#example_modaleditUser').modal('hide'); $("#example_modal3").attr("class", "alert alert-error"); //設置新樣式 $("#example_modal3 img").attr("src", "backstage/assets/img/error.png"); $("#message").text('修改失敗,請稍候再試!'); $("#example_modal3").css({position: "absolute", right: "600px", top: "20px",display:"block"}).width(300).height(20).show(5000); $('#example_modal3').delay(1500).hide(0); } },500); } </script>
七、HTML代碼
<!-- 消息提醒 --> <div class="alert alert-success" id="example_modal3" style="display: none ;width:300px;"> <button class="close" data-dismiss="alert" type="button">×</button> <img src="backstage/assets/img/success.png" width="30px;" height="30px;"/> <strong id="message">操做成功!</strong> </div>
3、blockUI配合ajax提升用戶體驗度
BlockUI 插件是用於進行AJAX操做時模擬同步傳輸時鎖定瀏覽器操做。當它被激活時,它會阻止使用者與頁面(或頁面的一部分)進行交互,直至它被取消。 BlockUI以在DOM中添加元素的方法來實現阻止用戶與瀏覽器交互的外觀和行爲。咱們能夠根據需求來設置遮罩樣式。更多demo能夠參考http://www.malsup.com/jquery/block/ 或者 http://www.fengfly.com/plus/view-213992-1.html
先給出一個ajax請求時鎖定頁面並加載gif動圖的例子:
一、頁面上導入blockUI插件js文件 固然必不可少的jQuery文件: (下載地址)
<script type="text/javascript" src="js/jquery.validate-1.13.1.js"></script> <script type="text/javascript" src="backstage/assets/js/jquery.blockUI.js"></script>
二、在須要動圖顯示的地方添加代碼:
<img id= "loading" src="images/loader4.gif" style="display:none;width:40px;height:40px;"/>
三、js內容
<script type="text/javascript"> function openAndClos(id){ $(document).ajaxStart(function(){ $.blockUI({ message: $('#loading'), css: { top: ($(window).height() - 400) /2 + 'px', left:($(window).width() - 200) /2 + 'px', width: '400px', border: 'none' }, overlayCSS:{backgroundColor: '#fff'} }); }).ajaxStop($.unblockUI); var args={"time":new Date()}; $.getJSON("searchMessage.action",args,function(data){ var count=data.counts; //....do something }); } </script>
4、ajax在jQuery validate中的運用
jquery.validate插件爲表單提供了強大的驗證功能,讓客戶端表單驗證變得更簡單,同時提供了大量的定製選項,知足應用程序各類需求。該插件捆綁了一套有用的驗證方法,包括 URL 和電子郵件驗證,同時提供了一個用來編寫用戶自定義方法的 API。具體使用講解請參考:http://www.runoob.com/jquery/jquery-plugin-validate.html
一樣的,給出一個異步校驗用戶註冊手機號重複的例子:
1)導入jquery.validate插件js文件 (下載地址)
<script type="text/javascript" src="js/jquery.validate-1.13.1.js"></script>
2)HTML代碼
<form action = "turnToregisterNext.action" method="post" class="register" id="regForm" autocomplete="off" > <label style="float:left;">註冊手機號</label> <input type="text" class="c_code_msg" style="margin-right: 10px;" name="phone" id="phone"/> <input type="submit" id="c_code_button" class="c_code_button" style="margin-right: 10px;" value="下一步"/> </form>
3)js代碼
<script type="text/javascript"> $("#regForm").validate({ // 添加驗證規則 rules: { phone:{ required: true, digits:true, rangelength:[11,11], remote: { url: "checkPhone.action", //後臺處理程序 type: "post", //數據發送方式 data: { //要傳遞的數據 phone: function() { return $("#phone").val(); } } } } }, //重設提示信息 messages:{ phone: { required: "請填寫手機號碼", digits:"請正確填寫手機號碼", rangelength: "手機號碼爲11位" , remote:"此手機已經註冊過" } } }); </script>
4)後臺處理程序
Struts配置:
<action name="checkPhone" class="UserBean" method="checkPhone"></action>
Action類:
public String checkPhone() throws IOException{ //0.手機號重複 1.不重複 int flag = 0; flag = ius.phoneHasReg(phone); //數據庫查詢返回值 HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); if(flag == 0) out.print(false); else out.print(true); return null; }