6.1 基于请求加载数据
6.1.1 追加HTML
html:
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="utf-8"> <title>The Devil's Dictionary</title> <link rel="stylesheet" href="06.css" type="text/css" /> <script src="jquery.js"></script> <script src="06.js"></script> </head> <body> <div id="container"> <div id="header"> <h2>The Devil's Dictionary</h2> <div class="author">by Ambrose Bierce</div> </div> <div class="letters"> <div class="letter" id="letter-a"> <h3><a href="#">A</a></h3> </div> <div class="letter" id="letter-b"> <h3><a href="#">B</a></h3> </div> <div class="letter" id="letter-c"> <h3><a href="#">C</a></h3> </div> <div class="letter" id="letter-d"> <h3><a href="#">D</a></h3> </div> <div class="letter" id="letter-e"> <h3>E</h3> <ul> <li><a href="e.PHP?term=Eavesdrop">Eavesdrop</a></li> <li><a href="e.PHP?term=Edible">Edible</a></li> <li><a href="e.PHP?term=Education">Education</a></li> <li><a href="e.PHP?term=Eloquence">Eloquence</a></li> <li><a href="e.PHP?term=Elysium">Elysium</a></li> <li><a href="e.PHP?term=Emancipation">Emancipation</a></li> <li><a href="e.PHP?term=Emotion">Emotion</a></li> <li><a href="e.PHP?term=Envelope">Envelope</a></li> <li><a href="e.PHP?term=Envy">Envy</a></li> <li><a href="e.PHP?term=Epitaph">Epitaph</a></li> <li><a href="e.PHP?term=Evangelist">Evangelist</a></li> </ul> </div> <div class="letter" id="letter-f"> <h3>F</h3> <form action="f.PHP"> <input type="text" name="term" value="" id="term" /> <button type="submit">Search</button> </form> </div> <div class="letter" id="letter-g"> <h3><a href="#">G</a></h3> </div> <div class="letter" id="letter-h"> <h3><a href="h.html">H</a></h3> </div> </div> <div id="dictionary"> </div> </div> </body> </html>
供插入的html:
<div class="entry"> <h3 class="term">ABDICATION</h3> <div class="part">n.</div> <div class="definition"> An act whereby a sovereign attests his sense of the high temperature of the throne. <div class="quote"> <div class="quote-line">Poor Isabella's Dead,whose abdication</div> <div class="quote-line">Set all tongues wagging in the Spanish nation.</div> <div class="quote-line">For that performance 'twere unfair to scold her:</div> <div class="quote-line">She wisely left a throne too hot to hold her.</div> <div class="quote-line">To History she'll be no royal riddle —</div> <div class="quote-line">Merely a plain parched pea that jumped the griddle.</div> <div class="quote-author">G.J.</div> </div> </div> </div> <div class="entry"> <h3 class="term">ABSOLUTE</h3> <div class="part">adj.</div> <div class="definition"> Independent,irresponsible. An absolute monarchy is one in which the sovereign does as he pleases so long as he pleases the assassins. Not many absolute monarchies are left,most of them having been replaced by limited monarchies,where the sovereign's power for evil (and for good) is greatly curtailed,and by republics,which are governed by chance. </div> </div> <div class="entry"> <h3 class="term">ACKNOWLEDGE</h3> <div class="part">v.t.</div> <div class="definition"> To confess. Acknowledgement of one another's faults is the highest duty imposed by our love of truth. </div> </div> <div class="entry"> <h3 class="term">AFFIANCED</h3> <div class="part">pp.</div> <div class="definition"> Fitted with an ankle-ring for the ball-and-chain. </div> </div> <div class="entry"> <h3 class="term">AMBIDEXTROUS</h3> <div class="part">adj.</div> <div class="definition"> Able to pick with equal skill a right-hand pocket or a left. </div> </div> <div class="entry"> <h3 class="term">ANOINT</h3> <div class="part">v.t.</div> <div class="definition"> To grease a king or other great functionary already sufficiently slippery. <div class="quote"> <div class="quote-line">As sovereigns are anointed by the priesthood,</div> <div class="quote-line">So pigs to lead the populace are greased good.</div> <div class="quote-author">Judibras</div> </div> </div> </div> <div class="entry"> <h3 class="term">ARMOR</h3> <div class="part">n.</div> <div class="definition"> The kind of clothing worn by a man whose tailor is a blacksmith. </div> </div>
加载html的js:
$(document).ready(function() { $('#letter-a a').click(function() { $('#dictionary').load('a.html'); return false; }); });
注意,下面的代码alert不一定在加载完成后执行,因为这个是ajax,这点很重要:
$(document).ready(function() { $('#letter-a a').click(function() { $('#dictionary').load('a.html'); alert('Loaded!'); return false; }); });
6.1.2 操作JavaScript对象
供加载的json:
[ { "term": "BACCHUS","part": "n.","definition": "A convenient deity invented by the ancients as an excuse for getting drunk.","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": "Jorace" },{ "term": "BACKBITE","part": "v.t.","definition": "To speak of a man as you find him when he can't find you." },{ "term": "BEARD","definition": "The hair that is commonly cut off by those who justly execrate the absurd Chinese custom of shaving the head." },{ "term": "BEGGAR","definition": "One who has relied on the assistance of his friends." },{ "term": "BELLADONNA","definition": "In Italian a beautiful lady; in English a deadly poison. A striking example of the essential identity of the two tongues." },{ "term": "BIGAMY","definition": "A mistake in taste for which the wisdom of the future will adjudge a punishment called trigamy." },{ "term": "BORE","definition": "A person who talks when you wish him to listen." } ]
加载json的js:
$('#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; html += '</div>'; html += '</div>'; }); $('#dictionary').html(html); }); return false; });
供加载的js:
var entries = [ { "term": "CALAMITY","definition": "A more than commonly plain and unmistakable reminder that the affairs of this life are not of our own ordering. Calamities are of two kinds: misfortune to ourselves,and good fortune to others." },{ "term": "CANNIBAL","definition": "A gastronome of the old school who preserves the simple tastes and adheres to the natural diet of the pre-pork period." },{ "term": "CHILDHOOD","definition": "The period of human life intermediate between the idiocy of infancy and the folly of youth — two removes from the sin of manhood and three from the remorse of age." },{ "term": "CLARIONET","definition": "An instrument of torture operated by a person with cotton in his ears. There are two instruments that are worse than a clarionet — two clarionets." },{ "term": "COMFORT","definition": "A state of mind produced by contemplation of a neighbor's uneasiness." },{ "term": "CORSAIR","definition": "A politician of the seas." } ]; var html = ''; $.each(entries,function() { html += '<div class="entry">'; html += '<h3 class="term">' + this.term + '</h3>'; html += '<div class="part">' + this.part + '</div>'; html += '<div class="definition">' + this.definition + '</div>'; html += '</div>'; }); $('#dictionary').html(html);
加载以上js的js:
$('#letter-c a').click(function() { $.getScript('c.js'); return false; });
供加载的xml文件:
<?xml version="1.0" encoding="UTF-8"?> <entries> <entry term="DANCE" part="v.i."> <definition> To leap about to the sound of tittering music,preferably with arms about your neighbor's wife or daughter. There are many kinds of dances,but all those requiring the participation of the two sexes have two characteristics in common: they are conspicuously innocent,and warmly loved by the vicIoUs. </definition> </entry> <entry term="DAY" part="n."> <definition> A period of twenty-four hours,mostly misspent. This period is divided into two parts,the day proper and the night,or day improper <![CDATA[—]]> the former devoted to sins of business,the latter consecrated to the other sort. These two kinds of social activity overlap. </definition> </entry> <entry term="DEBT" part="n."> <definition> An ingenIoUs substitute for the chain and whip of the slave-driver. </definition> <quote author="Barlow S. Vode"> <line>As,pent in an aquarium,the troutlet</line> <line>Swims round and round his tank to find an outlet,</line> <line>Pressing his nose against the glass that holds him,</line> <line>Nor ever sees the prison that enfolds him;</line> <line>So the poor debtor,seeing naught around him,</line> <line>Yet feels the narrow limits that impound him,</line> <line>Grieves at his debt and studies to evade it,</line> <line>And finds at last he might as well have paid it. </line> </quote> </entry> <entry term="DEFAME" part="v.t."> <definition> To lie about another. To tell the truth about another. </definition> </entry> <entry term="DEFENCELESS" part="adj."> <definition> Unable to attack. </definition> </entry> <entry term="DELIBERATION" part="n."> <definition> The act of examining one's bread to determine which side it is buttered on. </definition> </entry> <entry term="DELUSION" part="n."> <definition> The father of a most respectable family,comprising Enthusiasm,Affection,Self-denial,Faith,Hope,Charity and many other goodly sons and daughters. </definition> <quote author="Mumfrey Mappel"> <line>All hail,Delusion! Were it not for thee</line> <line>The world turned topsy-turvy we should see; </line> <line>For Vice,respectable with cleanly fancies,</line> <line>Would fly abandoned Virtue's gross advances. </line> </quote> </entry> <entry term="DENTIST" part="n."> <definition> A prestidigitator who,putting Metal into your mouth,pulls coins out of your pocket. </definition> </entry> <entry term="DIE" part="n."> <definition> The singular of "dice." We seldom hear the word,because there is a prohibitory proverb,"Never say die." At long intervals,however,some one says: "The die is cast," which is not true,for it is cut. The word is found in an immortal couplet by that eminent poet and domestic economist,Senator Depew: </definition> <quote> <line>A cube of cheese no larger than a die</line> <line>May bait the trap to catch a nibbling mie.</line> </quote> </entry> <entry term="DIPLOMACY" part="n."> <definition> The patriotic art of lying for one's country. </definition> </entry> <entry term="DISTANCE" part="n."> <definition> The only thing that the rich are willing for the poor to call theirs,and keep. </definition> </entry> </entries>
加载以上xml的js:
$('#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'); html += '</h3>'; html += '<div class="part">' + $entry.attr('part'); html += '</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; });
6.2 选择数据格式
html:
工作量小,但是不适合重用
json:
方便重用,但是解析发生错误的时候不会报错
javascript:
比较独特,不是一种存储数据的机制
xml:
xml文件大,加载慢
6.3 向服务器传递数据
6.3.1 执行get请求
执行get请求的js:
$('#letter-e a').click(function() { var requestData = {term: $(this).text()}; $.get('e.PHP',requestData,function(data) { $('#dictionary').html(data); }); return false; });
6.3.2 执行post请求
js:
$('#letter-e a').click(function() { var requestData = {term: $(this).text()}; $.post('e.PHP',function(data) { $('#dictionary').html(data); }); return false; });
load方法默认使用post方式加载
6.3.3 序列化表单
简单的表单:
<div class="letter" id="letter-f"> <h3>F</h3> <form action="f.PHP"> <input type="text" name="term" value="" id="term" /> <button type="submit">Search</button> </form> </div>
提交表单的一种方式:
$('#letter-f form').submit(function(event) { event.preventDefault(); $.get('f.PHP',{'term': $('input[name="term"]').val()},function(data) { $('#dictionary').html(data); }); });
另一种方式,较为推荐:
$('#letter-f form').submit(function(event) { event.preventDefault(); var formValues = $(this).serialize(); $.get('f.PHP',formValues,function(data) { $('#dictionary').html(data); }); });
6.4 为AJAX请求提供不同的内容
6.5 关注请求
检测ajax的开始和停止的js:
$('<div id="loading">Loading...</div>') .insertBefore('#dictionary') .ajaxStart(function() { $(this).show(); }).ajaxStop(function() { $(this).hide(); });
6.6 错误处理
可以在ajax后连缀success方法和comlete以及error方法:
$('#letter-e a').click(function() { var requestData = {term: $(this).text()}; $.get('z.PHP',function(data) { $('#dictionary').html(data); }).error(function(jqXHR) { $('#dictionary') .html('Sorry,but an error occurred: ' + jqXHR.status) .append(jqXHR.responseText); }); return false; });
6.7 AJAX和事件
使用ajax给文档添加新内容后,之前写的click方法不会起作用,需要使用live方法:
$('h3.term').live('click',function() { $(this).siblings('.definition').slideToggle(); });
6.8 安全限制
使用JSONP加载远程数据的js:
var url = 'http://examples.learningjquery.com/jsonp/g.PHP'; $('#letter-g a').click(function() { $.getJSON(url + '?callback=?',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>'; html += '</div>'; }); $('#dictionary').html(html); }); return false; });
6.9 其他工具
6.9.1 低级AJAX方法
与使用load加载html相同效果的:
$('#letter-a a').click(function() { $.ajax({ url: 'a.html',success: function(data) { $('#dictionary').html(data); } }); return false; });
6.9.2 修改默认选项
$('#letter-a a').click(function() { $.ajaxSetup({ url: 'a.html',type: 'POST',dataType: 'html' }); $.ajax({ type: 'GET',success: function(data) { $('#dictionary').html(data); } }); return false; });
6.9.3 部分加载HTML页面
js:
$('#letter-h a').click(function() { $('#dictionary').load('h.html .entry'); return false; });
6.10 小结
6.11 练习