這篇文章主要介紹了Jquery ajax基礎(chǔ)教程的相關(guān)資料,需要的朋友可以參考下
jQuery的Ajax帶來了無需刷新的web頁面革命。這里就詳細(xì)介紹一下jQuery所涉及到的Ajax操作。(無需特殊說明,均需要有服務(wù)器配置,這里本人用的是Tomcat 7)
1.基于請(qǐng)求加載文件數(shù)據(jù)
這里的請(qǐng)求通常都是網(wǎng)頁的某些操作,如點(diǎn)擊等。
而其加載數(shù)據(jù)的類型歸類為以下四種:a.加載HTML文件;b.加載JSON文件;c.加載Javascript文件;d.加載XML文件。
其對(duì)應(yīng)的四種加載方法分別是:load、getJSON、getScript、get。
a.加載HTML文件
把編寫好的HTML文件加載到網(wǎng)頁中。例如:
- //load方法加載html文件
- $('#letter-a a').click(function(){
- $('#dictionary').load('a.html');
- return false;
- });
這里a.html也是放在服務(wù)器端的一個(gè)已經(jīng)編寫好的頁面文件,直接調(diào)用load,就可以讓所匹配的目標(biāo)內(nèi)載入HTML內(nèi)容。
b.加載JSON文件
把編寫好的JSON文件加載到網(wǎng)頁中。例如:
- //加載json文件
- $('#letter-b a').click(function(){
- $.getJSON('b.json',function(data){
- var html = '';
- $.each(data,function(entryIndex, entry){
- html += "<div class='entry'>";
- html += "<h3 class='term'>" + entry.term + "</h3>";
- html += "<div class='part'>" + entry.part + "</div>";
- html += "<div class='definition'>";
- html += entry.definition;
- if(entry.quote){
- html += '<div class="quote">';
- $.each(entry.quote, function(lineIndex, line){
- html += '<div class="quote-line">' + line + '</div>';
- });
- if(entry.author){
- html += '<div class="quote-author">' + entry.author + '</div>';
- }
- }
- html += "</div>";
- html += "</div>";
- });
- $('#dictionary').html(html);
- });
- return false;
- });
getJSON方法第一個(gè)參數(shù)是指加載的文件路徑,第二個(gè)參數(shù)是一個(gè)加載完成以后的回調(diào)函數(shù)。通過這個(gè)回調(diào)函數(shù),就可以對(duì)加載好的data進(jìn)行操作。重復(fù)的部分使用each循環(huán)處理。最后將拼湊好的html字符串使用html方法加入到目標(biāo)id=dictionary的元素中。
c.加載Javascript文件
加載Javascript文件和加載HTML文件類似。這里需要注意的是,使用getScript方法加載進(jìn)來的Javascript會(huì)根據(jù)當(dāng)下Javascript環(huán)境直接運(yùn)行。例如:
- //執(zhí)行腳本
- $('#letter-c a').click(function(){
- $.getScript('c.js');
- return false;
- });
d.加載XML文件
jQuery中可以使用get方法加載XML文件。例如:
- //加載XML文檔
- $('#letter-d a').click(function(){
- $.get('d.xml',function(data){
- $('#dictionary').empty();
- $(data).find('entry').each(function(){
- var $entry = $(this);
- var html = '<div class="entry">';
- html += '<h3 class="term">' + $entry.attr('term') + '</h3>';
- html += '<div class="part">' + $entry.attr('part') + '</div>';
- html += '<div class="definition">';
- html += $entry.find('definition').text();
- var $quote = $entry.find('quote');
- if($quote.length)
- {
- html += '<div class="quote">';
- $quote.find('line').each(function(){
- html += '<div class="quote-line">';
- html += $(this).text() + '</div>';
- });
- if($quote.attr('author')){
- html += '<div class="quote-author">';
- html += $quote.attr('author') + '</div>';
- }
- html += '</div>';
- }
- html += '</div>';
- html += '</div>';
- $('#dictionary').append($(html));
- });
- });
- return false;
- });
XML文件有一個(gè)特點(diǎn)就是,你可以像用jQuery操作HTML那樣操作XML的那些元素。如使用attr方法、text方法等等。
2.基于Get方法向服務(wù)器獲取數(shù)據(jù)
之前的例子都是從服務(wù)器上靜態(tài)的獲取數(shù)據(jù)文件。而Ajax的價(jià)值不只于此,通過get方法從服務(wù)器動(dòng)態(tài)的獲取數(shù)據(jù),為web頁面無刷新的實(shí)現(xiàn)提供了莫大的幫助。
下面就使用get方法從服務(wù)器獲取一段所需要的數(shù)據(jù)。這里,本人結(jié)合J2EE的Struts2框架和TOMCAT搭建的服務(wù)器端。具體服務(wù)器端多種多樣,可以是php+apache或者其他什么的都可以。
操作如下,用戶點(diǎn)擊Eavesdrop則發(fā)送get方法到服務(wù)器,取得Eavesdrop的數(shù)據(jù),并且返回json值,然后在jQuery中裝配。
代碼如下:
- //GET方法加載服務(wù)器內(nèi)容
- $('#letter-e a').click(function(){
- var requestData = {term:$(this).text().toUpperCase()};
- $.get('EGet.action', requestData, function(data){
- //返回的數(shù)據(jù)包結(jié)構(gòu)根據(jù)Struts2配置如下:
- //{"resultMSG":"{ 內(nèi)部另一個(gè)json結(jié)構(gòu) }","success":"true"}
- //先將返回的數(shù)據(jù)包拆包
- var responseObj = eval("("+data+")");
- if(responseObj.success == 'true')
- {
- $('#dictionary').empty();
- //返回成功,接下來再次解包resultMSG
- var dataObj = eval("("+responseObj.resultMSG+")");
- var html = "";
- html += "<div class='entry'>";
- html += "<h3 class='term'>" + dataObj.term + "</h3>";
- html += "<div class='part'>" + dataObj.part + "</div>";
- html += "<div class='definition'>";
- html += dataObj.definition;
- if(dataObj.quote){
- html += '<div class="quote">';
- $.each(dataObj.quote, function(lineIndex, line){
- html += '<div class="quote-line">' + line + '</div>';
- });
- if(dataObj.author){
- html += '<div class="quote-author">' + dataObj.author + '</div>';
- }
- }
- html += "</div>";
- html += "</div>";
- $('#dictionary').html(html);
- }
- else
- {
- var $warning = $('<div>Sorry, your term was not found!</div>');
- $('#dictionary').html($warning);
- }
- });
- return false;
- });
這里要說明的是由于struts2配置,返回的時(shí)候在需要的數(shù)據(jù)外又打了一層包,用于表示結(jié)果內(nèi)容的resultMSG和是否ajax訪問成功的success字段。所以使用了2次eval解包。
這里我后臺(tái)java程序傳遞過來的并非配置好的HTML,而是僅僅是json類型的數(shù)據(jù),本人認(rèn)為在java層面編寫html并傳遞不如直接傳遞數(shù)據(jù)方便,以后修改樣式或者頁面結(jié)構(gòu)也都不如直接修改javascript方便。
通過get方法獲得服務(wù)器數(shù)據(jù),相當(dāng)于向服務(wù)器提交如下這種請(qǐng)求:EGet.action?term=XXX
下面放出java后臺(tái)文件代碼:
1.EGet.java
- package lhb;
- import com.opensymphony.xwork2.ActionSupport;
- public class EGet extends ActionSupport
- {
- private String term;
- private Terms sampleTerm;
- private String success;
- private String resultMSG;
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public String execute() throws Exception
- {
- initData();
- if(term.equals(sampleTerm.getTerm()))
- {
- success = "true";
- resultMSG = "{/"term/": /""+sampleTerm.getTerm()+"/","+
- "/"part/": /""+sampleTerm.getPart()+"/","+
- "/"definition/": /""+sampleTerm.getDefinition()+"/","+
- "/"quote/": ["+
- "/"Is public worship, then, a sin,/","+
- "/"That for devotions paid to Bacchus/","+
- "/"The lictors dare to run us in,/","+
- "/"And resolutely thump and whack us?/""+
- "],"+
- "/"author/": /""+sampleTerm.getAuthor()+"/"}";
- }
- else{
- success = "false";
- resultMSG = "fail";
- }
- return SUCCESS;
- }
- //初始化數(shù)據(jù)
- private void initData()
- {
- String partEAVESDROP = "v.i.";
- String definitionEAVESDROP = "Secretly to overhear a catalogue of the crimes and vices of another or yourself.";
- String quoteEAVESDROP[] = {"A lady with one of her ears applied",
- "To an open keyhole heard, inside,",
- "Two female gossips in converse free —",
- "The subject engaging them was she.",
- "/"I think,/" said one, /"and my husband thinks",
- "That she's a prying, inquisitive minx!/"",
- "As soon as no more of it she could hear",
- "The lady, indignant, removed her ear.",
- "/"I will not stay,/" she said, with a pout,",
- "/"To hear my character lied about!/""};
- String authorEAVESDROP = "Gopete Sherany";
- Terms EAVESDROP = new Terms();
- EAVESDROP.setTerm("EAVESDROP");
- EAVESDROP.setPart(partEAVESDROP);
- EAVESDROP.setDefinition(definitionEAVESDROP);
- EAVESDROP.setQuote(quoteEAVESDROP);
- EAVESDROP.setAuthor(authorEAVESDROP);
- sampleTerm = EAVESDROP;
- }
- public String getTerm()
- {
- return term;
- }
- public void setTerm(String term)
- {
- this.term = term;
- }
- public String getSuccess()
- {
- return success;
- }
- public void setSuccess(String success)
- {
- this.success = success;
- }
- public String getResultMSG()
- {
- return resultMSG;
- }
- public void setResultMSG(String resultMSG)
- {
- this.resultMSG = resultMSG;
- }
- }
這個(gè)action中的數(shù)據(jù)本人直接配置了,這里只是做一個(gè)示范使用。真正的這些數(shù)據(jù)在項(xiàng)目中一般是存放在數(shù)據(jù)庫中的。由于這主要是jQuery方面的小示例,就不弄那么麻煩了。
2.Terms.java
- package lhb;
- public class Terms
- {
- private String term;
- private String part;
- private String definition;
- private String quote[];
- private String author;
- public String getTerm()
- {
- return term;
- }
- public void setTerm(String term)
- {
- this.term = term;
- }
- public String getPart()
- {
- return part;
- }
- public void setPart(String part)
- {
- this.part = part;
- }
- public String getDefinition()
- {
- return definition;
- }
- public void setDefinition(String definition)
- {
- this.definition = definition;
- }
- public String[] getQuote()
- {
- return quote;
- }
- public void setQuote(String[] quote)
- {
- this.quote = quote;
- }
- public String getAuthor()
- {
- return author;
- }
- public void setAuthor(String author)
- {
- this.author = author;
- }
- }
這個(gè)類純粹就是一個(gè)pojo類。沒有什么特別的方法。
3.struts.xml
這個(gè)是struts2的json方式傳遞配置
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
- "http://struts.apache.org/dtds/struts-2.3.dtd">
- <struts>
- <!-- 指定全局國際化資源文件 -->
- <constant name="struts.custom.i18n.resources" value="i18n"/>
- <!-- 指定國際化編碼所使用的字符集 -->
- <constant name="struts.i18n.encoding" value="GBK"/>
- <!-- JSON的action -->
- <package name="jsonInfo" extends="json-default">
- <action name="EGet" class="lhb.EGet">
- <result type="json">
- <param name="contentType">text/html</param>
- <param name="includeProperties">success, resultMSG</param>
- </result>
- </action>
- </package>
- </struts>
這里可以看到includeProperties里所配置的外面一層json,success和resultMSG。這在實(shí)際中很好用。如果服務(wù)器中沒有取得需要的值,雖然ajax訪問成功,但是獲得的結(jié)果并不算成功,因?yàn)闆]有取得需要的值。這里加入了success標(biāo)示,方便前臺(tái)jQuery操作。
基于其他方法獲取服務(wù)器數(shù)據(jù)從寫法上與get基本一致,如post方法、load方法。這里就不再贅述了。
3.動(dòng)態(tài)提交表單
通過jQuery的AJAX支持,可以讓我們很方便的動(dòng)態(tài)提交表單而不用刷新頁面。
如下面例子:
- $('#letter-f form').submit(function(){
- //調(diào)用preventDefault方法阻止事件冒泡,具體工作就是如果網(wǎng)頁有腳本錯(cuò)誤,那么則會(huì)阻止提交form表單
- event.preventDefault();
- var formValues = $('input[id="term"]').val();
- var requestStr = {'term':formValues.toUpperCase()};
- $.get('EGet.action', requestStr, function(data){
- var responseObj = $.parseJSON(data);
- if(responseObj.success == 'true')
- {
- var html = '';
- var dataObj = $.parseJSON(responseObj.resultMSG);
- html += "<div class='entry'>";
- html += "<h3 class='term'>" + dataObj.term + "</h3>";
- html += "<div class='part'>" + dataObj.part + "</div>";
- html += "<div class='definition'>";
- html += dataObj.definition;
- if(dataObj.quote){
- html += '<div class="quote">';
- $.each(dataObj.quote, function(lineIndex, line){
- html += '<div class="quote-line">' + line + '</div>';
- });
- if(dataObj.author){
- html += '<div class="quote-author">' + dataObj.author + '</div>';
- }
- }
- html += "</div>";
- html += "</div>";
- $('#dictionary').html(html);
- }
- else{
- var warning = $('Sorry, your term was not found!');
- $('#dictionary').html(warning);
- }
- });
- });
這個(gè)例子援引的數(shù)據(jù)還是上一個(gè)EGet.action所用的那個(gè)數(shù)據(jù)。程序的操作過程基本是:
首先調(diào)用這個(gè) preventDefault();這個(gè)方法在注釋里也說明了,用于阻止事件冒泡帶來的不便與麻煩。
接下來通過$()獲得input的元素,使用val方法獲得其值,接下來的使用方法與上例基本相同。
這里也可以使用serialize方法將input元素序列化成如下格式“term=xxx”這樣。不過由于服務(wù)器端的java程序中的那些數(shù)據(jù)時(shí)硬編碼的,所有,不是太方便用,就沒用。
4.關(guān)于Ajax的觀察員函數(shù)
jQuery包含了2個(gè)全局的ajax觀察員函數(shù):ajaxStart和ajaxStop。
分別在執(zhí)行ajax操作的起始和結(jié)束時(shí)調(diào)用。例如:
- //ajax的觀察員函數(shù) ajaxStart 和 ajaxStop
- $('<div id="loading">Loading...</div>').insertBefore('#dictionary')
- .ajaxStart(function(){
- $(this).show();
- }).ajaxStop(function(){
- $(this).hide();
- });
這里無論哪個(gè)a標(biāo)簽觸發(fā)ajax操作,包括靜態(tài)載入文件和動(dòng)態(tài)服務(wù)器訪問,都會(huì)觸發(fā)ajaxStart和ajaxStop。
關(guān)于錯(cuò)誤處理,常用的三個(gè)函數(shù):success、complete、error。
下面以error為例:
- .error(function(jqXHR){
- $('#dictionary').html('An Error occurred:'+ jqXHR.status).append(jqXHR.responseText);
- });
可以以連綴的寫法將error方法放置于get方法之后:“$.get().error()”這樣。
剛才看了一下,這個(gè)可以將Tomcat的報(bào)錯(cuò),加載到頁面之上。這在有的時(shí)候還是很有用的。如圖:
不過不知道為何這個(gè)將我原有樣式也覆蓋了一些,如果有哪位網(wǎng)友知道,麻煩指正一下問題所在。謝謝了。
5.Ajax和事件
Ajax動(dòng)態(tài)訪問服務(wù)器以后生成的元素,如果想綁定事件的話,一種方法是每次取到都重新綁定處理程序,這種相對(duì)來說比較簡單,但是不適合DOM結(jié)構(gòu)經(jīng)常變化的場景。如果DOM結(jié)構(gòu)經(jīng)常變化,那么就需要用live方法,實(shí)現(xiàn)事件委托。
live用法與bind一樣。
關(guān)于jquery ajax基礎(chǔ)教程今天小編就給大家介紹到這里,后續(xù)還會(huì)持續(xù)給大家介紹,希望大家繼續(xù)關(guān)注腳本之家網(wǎng)站,有你們的關(guān)注我們會(huì)做的更好,謝謝!
新聞熱點(diǎn)
疑難解答
圖片精選