jQuery’s Ajax brings a web page revolution that doesn’t require refreshing. Here is a detailed introduction to the Ajax operations involved in jQuery. (No special instructions are required, server configuration is required. I am using Tomcat 7 here)
1. Load file data based on request
The requests here are usually certain operations on the web page, such as clicks, etc.
The types of data loaded are classified into the following four types: a. Loading HTML files; b. Loading JSON files; c. Loading Javascript files; d. Loading XML files.
The corresponding four loading methods are: load, getJSON, getScript, get.
a. Load HTML file
Load the written HTML file into the web page. For example:
//load方法加载html文件 $('#letter-a a').click(function(){ $('#dictionary').load('a.html'); return false; });
Here a.html is also a pre-written page file placed on the server side. Calling load directly will allow the HTML content to be loaded into the matched target.
b. Load JSON file
Load the prepared JSON file into the web page. For example:
//加载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; });
The first parameter of the getJSON method refers to the loaded file path, and the second parameter is a callback function after the loading is completed. Through this callback function, you can operate on the loaded data. Repeated parts are processed using each loop. Finally, use the html method to add the assembled html string to the element with the target id=dictionary.
c. Load Javascript file
Loading Javascript files is similar to loading HTML files. What needs to be noted here is that the Javascript loaded using the getScript method will be run directly according to the current Javascript environment. For example:
//执行脚本 $('#letter-c a').click(function(){ $.getScript('c.js'); return false; });
d. Load XML file
You can use the get method to load XML files in jQuery. For example:
//加载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; });
One feature of XML files is that you can operate XML elements just like you use jQuery to operate HTML. Such as using attr method, text method, etc.
2. Obtain data from the server based on the Get method
The previous examples all statically obtained data files from the server. The value of Ajax is not limited to this. It dynamically obtains data from the server through the get method, which provides great help for the realization of web pages without refreshing.
Next, use the get method to obtain a piece of required data from the server. Here, I built the server side by combining J2EE's Struts2 framework and TOMCAT. The specific server side is diverse, it can be php apache or anything else.
The operation is as follows. When the user clicks Eavesdrop, the get method is sent to the server, the Eavesdrop data is obtained, and the json value is returned, which is then assembled in jQuery.
The code is as follows:
//GET方法加载服务器内容 $('#letter-e a').click(function(){ var requestData = {term:$(this).text().toUpperCase()}; $.get('EGet.action', requestData, function(data){ //返回的数据包结构根据Struts2配置如下: //{"resultMSG":"{ 内部另一个json结构 }","success":"true"} //先将返回的数据包拆包 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; });
What should be explained here is that due to the struts2 configuration, when returning, there is another layer of packaging in addition to the required data, which is the resultMSG used to represent the result content and the success field whether the ajax access is successful. So two eval unpackings were used.
What my background Java program passes here is not the configured HTML, but only json type data. I think writing and transmitting HTML at the Java level is not as convenient as directly passing the data, and it is not as convenient to modify the style or page structure in the future. It is convenient to modify javascript directly.
Obtaining server data through the get method is equivalent to submitting the following request to the server: EGet.action?term=XXX
The java background file code is released below:
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; } //初始化数据 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; } }
The data in this action is configured directly by myself, and it is only used as a demonstration here. The real data is generally stored in the database in the project. Since this is mainly a small example of jQuery, I won't go into too much trouble.
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; } }
This class is purely a pojo class. There is no special method.
3.struts.xml
This is the json method of struts2 to transfer configuration
<?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>
Here you can see the outer layer json, success and resultMSG configured in includeProperties. This works well in practice. If the required value is not obtained from the server, although the ajax access is successful, the result obtained is not considered successful because the required value is not obtained. The success mark is added here to facilitate front-end jQuery operations.
Obtaining server data based on other methods is basically the same as get in terms of writing, such as post method and load method. I won’t go into details here.
3. Dynamically submit the form
With jQuery’s AJAX support, we can easily submit forms dynamically without refreshing the page.
As an example below:
$('#letter-f form').submit(function(){ //调用preventDefault方法阻止事件冒泡,具体工作就是如果网页有脚本错误,那么则会阻止提交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); } }); });
这个例子援引的数据还是上一个EGet.action所用的那个数据。程序的操作过程基本是:
首先调用这个 preventDefault();这个方法在注释里也说明了,用于阻止事件冒泡带来的不便与麻烦。
接下来通过$()获得input的元素,使用val方法获得其值,接下来的使用方法与上例基本相同。
这里也可以使用serialize方法将input元素序列化成如下格式“term=xxx”这样。不过由于服务器端的java程序中的那些数据时硬编码的,所有,不是太方便用,就没用。
4.关于Ajax的观察员函数
jQuery包含了2个全局的ajax观察员函数:ajaxStart和ajaxStop。
分别在执行ajax操作的起始和结束时调用。例如:
//ajax的观察员函数 ajaxStart 和 ajaxStop $('<div id="loading">Loading...</div>').insertBefore('#dictionary') .ajaxStart(function(){ $(this).show(); }).ajaxStop(function(){ $(this).hide(); });
这里无论哪个a标签触发ajax操作,包括静态载入文件和动态服务器访问,都会触发ajaxStart和ajaxStop。
关于错误处理,常用的三个函数:success、complete、error。
下面以error为例:
.error(function(jqXHR){ $('#dictionary').html('An Error occurred:'+ jqXHR.status).append(jqXHR.responseText); });
可以以连缀的写法将error方法放置于get方法之后:“$.get().error()”这样。
刚才看了一下,这个可以将Tomcat的报错,加载到页面之上。这在有的时候还是很有用的。如图:
不过不知道为何这个将我原有样式也覆盖了一些,如果有哪位网友知道,麻烦指正一下问题所在。谢谢了。
5.Ajax和事件
Ajax动态访问服务器以后生成的元素,如果想绑定事件的话,一种方法是每次取到都重新绑定处理程序,这种相对来说比较简单,但是不适合DOM结构经常变化的场景。如果DOM结构经常变化,那么就需要用live方法,实现事件委托。
live用法与bind一样。
关于jquery ajax基础教程今天小编就给大家介绍到这里,后续还会持续给大家介绍,希望大家继续关注脚本之家网站,有你们的关注我们会做的更好,谢谢!