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","part": "n.","definition": "The hair that is commonly cut off by those who justly execrate the absurd Chinese custom of shaving the head."},{"term": "BEGGAR","part": "n.","definition": "One who has relied on the assistance of his friends."},{"term": "BELLADONNA","part": "n.","definition": "In Italian a beautiful lady; in English a deadly poison.  A striking example of the essential identity of the two tongues."},{"term": "BIGAMY","part": "n.","definition": "A mistake in taste for which the wisdom of the future will adjudge a punishment called trigamy."},{"term": "BORE","part": "n.","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","part": "n.","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","part": "n.","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","part": "n.","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","part": "n.","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","part": "n.","definition": "A state of mind produced by contemplation of a neighbor's uneasiness."},{"term": "CORSAIR","part": "n.","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 ordaughter.  There are many kinds of dances, but allthose requiring the participation of the two sexes havetwo characteristics in common: they are conspicuouslyinnocent, and warmly loved by the vicious.</definition></entry><entry term="DAY" part="n."><definition>A period of twenty-four hours, mostly misspent.  Thisperiod is divided into two parts, the day proper andthe night, or day improper <![CDATA[—]]> theformer devoted to sins of business, the latterconsecrated to the other sort.  These two kinds ofsocial activity overlap.</definition></entry><entry term="DEBT" part="n."><definition>An ingenious substitute for the chain and whip of theslave-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 anoutlet,</line><line>Pressing his nose against the glass that holdshim,</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 whichside it is buttered on.</definition></entry><entry term="DELUSION" part="n."><definition>The father of a most respectable family, comprisingEnthusiasm, 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 saydie."  At long intervals, however, some one says:  "Thedie is cast," which is not true, for it is cut.  Theword is found in an immortal couplet by that eminentpoet 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 poorto 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', requestData, 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', requestData, 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=?', 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>';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 练习

06_通过AJAX发送数据相关推荐

  1. jquery 获取键值对中最大值_jQuery的AJAX发送数据键值对

    在我的aspx页面,我对JS是这样的: -jQuery的AJAX发送数据键值对 $("#btnLoad").click(function() { var dataForAjax = ...

  2. JS实现的ajax发送数据重复

    最近在做一个网页聊天室,但是在用ajax实现异步处理的时候,向服务器发送数据发送了两次,导致,我说一句会有两句回复. 先来看一下代码,问题主要还是出现在前端: <form id="da ...

  3. ajax发送数据时的contentType

    contentType: 指明发送的data数据(这里是aa)的类型 参数值:application/x-www-form-urlencoded(默认) 特点: 以key/value为一组使用& ...

  4. Django10:Ajax介绍/发送数据/SweetAlert

    Ajax 异步提交 局部刷新 发送方式 1. 浏览器输入url,按enter       get 2.a标签href属性                       get 3.form表单      ...

  5. ajax发送请求的数据结构

    ajax前后端的数据交互 1.ajax 发送字符串类型 前端: // 发送ajax测试数据$.ajax({url: "settings/test/ajaxStr/toRecStr.do&qu ...

  6. 原生php ajax post_使用原生ajax发送post请求完整案例

    搜索热词 使用ajax发送数据实现前后台的交互,我想是web开发最基础的技能了.近来dz开发因为不兼容jquery,所以只能使用原生js发送数据,不想还遇到很多问题.在这里分析总结一下.先来一个使用a ...

  7. 如何在客户端发送ajax请求,ajax - 从服务器(nodejs)发送数据到客户端(ajax请求)

    如何使用nodejs将数据从服务器发送到客户端? 所以基本上我通过点击一个按钮来调用这个函数 javascriptfunction createStuff(tid) { $.ajax({ type: ...

  8. JQ中使用FormData+Ajax发送请求及使用express接收处理FormData数据

    JQ中使用FormData+Ajax发送请求及使用express接收处理FormData数据 最近写大创项目的时候,要做登录功能,考虑到之后还需要上传头像图片,因此决定使用FormData发送表单请求 ...

  9. ajax发送请求和数据返回,Ajax发送和接收请求

    首先Ajax的不刷新页面提交数据 基本上浏览器能接收的信息,Ajax都可以接收,ex:字符串,html标签,css标签,xml格式内容,json格式内容等等..... // IE浏览器 if(Acti ...

最新文章

  1. jquery选择器的使用方式
  2. 6 js 比较两个数组的差异_每天一道算法题(js)(3)——寻找两个有序数组的中位数...
  3. git bash学习3 -简单杂乱知识点记录
  4. Intellij Idea 创建Web项目入门(一)
  5. python3 的 str bytes 区别
  6. 给计算机系统的资产分配的记号被称为什么,哈工大2015计算机复试试题(25页)-原创力文档...
  7. java正则表达式性能_译:Java 中的正则表达式性能概述
  8. Python基于用户协同过滤算法电影推荐的一个小改进
  9. 第 10 章 对象的实例化内存布局与访问定位
  10. 自定义属性-模态框的改进
  11. intra调用order
  12. matlab 色温图,LED色温图谱详解
  13. springboot2集成sharding-jdbc分库分表
  14. beeline软件_Beeline
  15. 解决谷歌浏览器打开是2345主页的问题
  16. android-studio推荐模拟器,Android studio 三大模拟器比较,强烈推荐第三种
  17. 2.3 连续性随机变量
  18. 屏幕尺寸、分辨率、像素密度及其三者之间的关系
  19. 02) android studio 创建安卓虚拟机,使用虚拟机调试
  20. java ebcdic编码转换_EBCDIC编码转换为ASCII编码

热门文章

  1. AI语音定制化,将给2020带来三个可能
  2. 趣图:最近火的一些程序员成语
  3. 请问各位如何用Delphi控制U盘的安全拔出????已经有源代码,但是不知道如何控制指定的U盘...
  4. php网站系统说明,phpweb成品网站文件系统结构说明
  5. SSH的工作原理、加密方式以及配置多个ssh key
  6. android导入工程以后报错,Android 导入v7包常见错误,以及项目引用v7包错误解决...
  7. 目标跟踪领域研究(一)Benchmark
  8. 家居vr全景展示制作提高客户转化
  9. 洛谷-5043 【模板】树同构([BJOI2015]树的同构)
  10. 1.异常简介:什么是异常???常见异常有哪些???