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 练习

06_通过AJAX发送数据的更多相关文章

  1. HTML实现代码雨源码及效果示例

    这篇文章主要介绍了HTML实现代码雨源码及效果示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  2. html5 拖拽及用 js 实现拖拽功能的示例代码

    这篇文章主要介绍了html5 拖拽及用 js 实现拖拽,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  3. HTML文本属性&amp;颜色控制属性的实现

    这篇文章主要介绍了HTML文本属性&颜色控制属性的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  4. 简洁自适应404页面HTML好看的404源码

    这篇文章主要介绍了简洁自适应404页面HTML好看的404源码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  5. amaze ui 的使用详细教程

    这篇文章主要介绍了amaze ui 的使用详细教程,本文通过多种方法给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. HTML5适合的情人节礼物有纪念日期功能

    这篇文章主要介绍了HTML5适合的情人节礼物有纪念日期功能,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  7. 如何给HTML标签中的文本设置修饰线

    这篇文章主要介绍了如何给HTML标签中的文本设置修饰线,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  8. HTML5调用手机发短信和打电话功能

    这篇文章主要介绍了HTML5调用手机发短信和打电话功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  9. HTML利用九宫格原理进行网页布局

    这篇文章主要介绍了HTML利用九宫格原理进行网页布局,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  10. HTML中实现音乐或视频自动播放案例详解

    由于期末大作业我想插入一个背景音乐,实现点开网页就会自动播放音频的效果,今天通过本文给大家分享下我基于HTML实现音乐或视频自动播放功能,代码简单易懂,需要的朋友参考下吧

随机推荐

  1. xe-ajax-mock 前端虚拟服务

    最新版本见Github,点击查看历史版本基于XEAjax扩展的Mock虚拟服务插件;对于前后端分离的开发模式,ajax+mock使前端不再依赖后端接口开发效率更高。CDN使用script方式安装,XEAjaxMock会定义为全局变量生产环境请使用xe-ajax-mock.min.js,更小的压缩版本,可以带来更快的速度体验。

  2. vue 使用 xe-ajax

    安装完成后自动挂载在vue实例this.$ajaxCDN安装使用script方式安装,VXEAjax会定义为全局变量生产环境请使用vxe-ajax.min.js,更小的压缩版本,可以带来更快的速度体验。cdnjs获取最新版本点击浏览已发布的所有npm包源码unpkg获取最新版本点击浏览已发布的所有npm包源码AMD安装require.js安装示例ES6Module安装通过Vue.use()来全局安装示例./Home.vue

  3. AJAX POST数据中文乱码解决

    前端使用encodeURI进行编码后台java.net.URLDecoder进行解码编解码工具

  4. Koa2框架利用CORS完成跨域ajax请求

    实现跨域ajax请求的方式有很多,其中一个是利用CORS,而这个方法关键是在服务器端进行配置。本文仅对能够完成正常跨域ajax响应的,最基本的配置进行说明。这样OPTIONS请求就能够通过了。至此为止,相当于仅仅完成了预检,还没发送真正的请求呢。

  5. form提交时,ajax上传文件并更新到&lt;input&gt;中的value字段

  6. ajax的cache作用

    filePath="+escape;},error:{alert;}});解决方案:1.加cache:false2.url加随机数正常代码:网上高人解读:cache的作用就是第一次请求完毕之后,如果再次去请求,可以直接从缓存里面读取而不是再到服务器端读取。

  7. 浅谈ajax上传文件属性contentType = false

    默认值为contentType="application/x-www-form-urlencoded".在默认情况下,内容编码类型满足大多数情况。在这里,我们主要谈谈contentType=false.在使用ajax上传文件时:在其中先封装了一个formData对象,然后使用post方法将文件传给服务器。说到这,我们发现在JQueryajax()方法中我们使contentType=false,这不是冲突了吗?这就是因为当我们在form标签中设置了enctype=“multipart/form-data”,

  8. 909422229_ajaxFileUpload上传文件

    ajaxFileUpload.js很多同名的,因为做出来一个很容易。我上github搜AjaxFileUpload出来很多类似js。ajaxFileUpload是一个异步上传文件的jQuery插件传一个不知道什么版本的上来,以后不用到处找了。语法:$.ajaxFileUploadoptions参数说明:1、url上传处理程序地址。2,fileElementId需要上传的文件域的ID,即的ID。3,secureuri是否启用安全提交,默认为false。4,dataType服务器返回的数据类型。6,error

  9. AJAX-Cache:一款好用的Ajax缓存插件

    原文链接AJAX-Cache是什么Ajax是前端开发必不可少的数据获取手段,在频繁的异步请求业务中,我们往往需要利用“缓存”提升界面响应速度,减少网络资源占用。AJAX-Cache是一款jQuery缓存插件,可以为$.ajax()方法扩展缓存功能。

  10. jsf – Ajax update/render在已渲染属性的组件上不起作用

    我试图ajax更新一个有条件渲染的组件。我可以确保#{user}实际上是可用的。这是怎么引起的,我该如何解决呢?必须始终在ajax可以重新呈现之前呈现组件。Ajax正在使用JavaScriptdocument.getElementById()来查找需要更新的组件。但是如果JSF没有将组件放在第一位,那么JavaScript找不到要更新的内容。解决方案是简单地引用总是渲染的父组件。

返回
顶部