首页 > JavaScript > jQuery getJSON()函数及getScript()函数
2009七月1

jQuery getJSON()函数及getScript()函数

看这俩函数名,我们都知道get是获取的意思,也是面向对象编程里面经常用到的一个单词,getScript()函数我们可以猜其是获取javaScript文件,那getJson()应该是获取json文件喽?可是json是什么?

这一篇日志,通过getJson()函数和getScript()函数来继续上一篇日志的字典示例。

在介绍代码之前,我认为有必要介绍一下json,这个重量级的选手。

json:

我们都知道,JavaScript的对象和数组都是key,value对,其实我之前的文章里面也介绍过,JavaScript的数组和对象本质上是相同的。

而json,我们可以理解为以JavaScript对象直接量的形式表现的数据类型,也可以将此对象直接量直接存入文件中。

json和JavaScript的对象直接量一样,使用花括号({})来定义,但是如果我的值的映射为数组咋办?别急,在json里,数组可以用数组直接量来表示,使用方括号([])来定义

json格式很简单,但是它却不允许有任何错误,所有方括号、花括号、引号和逗号都必须合理而且适当地存在,否则文件不会加载。

例如:

{
"xiaoxiaozi":{"name":"simaopig","siteurl":"http://www.xiaoxiaozi.com"},
"laonb":{"name":"laonb","siteurl":"http://www.laonb.com"},
"晚餐":["煮串","棒棒鸡","猪耳朵"]
}

有兴趣深入了解的同学可以去访问http://json.org

getJSON():

同样,先来看一下getJson的使用方法 jQuery.getJSON(url,[data],[callback])

参数同上一节说过的.load()函数

要获得一个json文件的内容,就可以使用$.getJSON()方法,这个方法会在取得相应文件后对文件进行处理,并将处理得到的JavaScript对象提供给代码。

回调函数提供了一种等候数据返回的方式,而不是立即执行代码,回调函数也需要一个参数,该参数中保存着返回的数据。这样我们就可能使用jQuery提供的另一个全局函数(类方法).each()来实现循环操作,将.getJSON函数返回的每组数据循环处理。

getScript():

该函数是向页面中注入脚本,这与加载一个HTML片段是一样的简单,不过此方法只提供两个参数,jQuery.getScript(url,[callback])

至于为什么没有data,呃,难道你认为js文件能接收参数吗?

getJSON()与ajax请求实战:

点击字母”B”下面的按钮我们来用getJSON()的方式从b.json中加载以“字母B”开头的单词

<div class="letter" id="letter-b">
    <h3>B</h3>
    <div class="button">Load</div>        
</div>
<!-- 用css文件定义id为loading的div的样式为display:none -->
<div id="loading">
    Loading...
</div>
<div id="dictionary">
</div>

定义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."
  }
]
$(document).ready(function() {
  // 字母B下面的按钮被点击时触发发函数
  $('#letter-b .button').click(function() {
    // 加载b.json文件的内容
    $.getJSON('b.json', function(data) {
      // 先将id为dictionary的div里的内容置空
      $('#dictionary').empty();
      // 循环处理每条返回的数据entryIndex为每一行数组的key,entry为数组的value
      $.each(data, function(entryIndex, entry) {
         // 拼装要显示的内容
        var 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>';
        // id为dictionary里放入html
        $('#dictionary').append(html);
      });
    });
  });
});

getScript()与ajax请求实战:

点击字母”C”下面的按钮我们来用getScript()的方式从c.js中加载以“字母C”开头的单词

<div class="letter" id="letter-c">
    <h3>C</h3>
    <div class="button">Load</div>        
</div>
<!-- 用css文件定义id为loading的div的样式为display:none -->
<div id="loading">
    Loading...
</div>
<div id="dictionary">
</div>

c.js文件的内容

// 定义entries 数组
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."
  }
]

// 拼显示的内容
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>';
});

// id为dictionary的innerHTML改为html
$('#dictionary').html(html);
$(document).ready(function() {
  // 点击字母C下面的按钮,用getScript函数请求c.js文件
  $('#letter-c .button').click(function() {
    $.getScript('c.js');
  });
});

文章作者:simaopig
本文地址:http://www.xiaoxiaozi.com/2009/07/01/1054/
版权所有 © 转载时必须以链接形式注明作者和原始出处!

13 Responses to “jQuery getJSON()函数及getScript()函数”

  1. #1 卢松松 回复 | 引用 Post:2009-07-02 13:31

    这标题……汗!~又是技术笔记吧

    [回复]

  2. #2 simaopig 回复 | 引用 Post:2009-07-02 14:00

    @卢松松
    嗯。是滴。。呵呵。

    [回复]

  3. #3 simaopig 回复 | 引用 Post:2009-07-02 14:08

    演示地址已经更换为本站地址。可以访问了。。

    呜,我可怜的国外空间啊。。

    [回复]

  4. #4 bolo 回复 | 引用 Post:2009-07-02 17:37

    用js做ajax?感觉有点烦

    [回复]

  5. #5 simaopig 回复 | 引用 Post:2009-07-02 17:37

    @bolo
    嗯,这个虽然很少有人用,不过有的时候也是会用到的。偶尔,偶尔。呵呵。

    [回复]

  6. #6 平平 回复 | 引用 Post:2009-07-02 18:23

    :evil: 完全不知道在说什么。

    [回复]

  7. #7 simaopig 回复 | 引用 Post:2009-07-02 18:24

    @平平
    呃,那就和我一起,呼,吸。“呼”,“吸”。。。 :D

    [回复]

  8. #8 壞壞男孩 回复 | 引用 Post:2010-01-21 09:42

    讲的好! ;-)

    [回复]

  9. #9 simaopig 回复 | 引用 Post:2010-01-21 10:01

    @壞壞男孩
    呵呵,谢谢。。 :smile:

    [回复]

  10. #10 泥菩萨 回复 | 引用 Post:2011-06-10 18:45

    :mrgreen: 想不到我们用一样的模板。更加想不到的是我们遇到了同一问题。。。这两天为淘宝客的智能提示烦恼。开始想捡便宜。最后心一横。干脆自己弄一个。反正jq有现在的东西。自己只须要做很少的事就行 了。

    [回复]

  11. #11 zara 回复 | 引用 Post:2011-10-18 10:12

    很好的学习笔记 :twisted:

    [回复]

  12. #12 小风 回复 | 引用 Post:2012-01-09 09:20

    楼主,请问下,ajax跨域的东西,能否赐教下,谢谢了

    [回复]

  13. #13 simaopig 回复 | 引用 Post:2012-01-09 14:32

    @小风
    谈不上赐教,咱们一起研究吧。 关于jsonp你可以去搜一下相关资料!

    [回复]

发表评论

:wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :?: :-| :-x :-o :-P :-D :-? :) :( :!: 8-O 8)