天涯之外

导航

客户端结合javascript调用JSON的例子

前面我已经介绍过what is json,下面我通过实例来学习在客户端结合javascript调用JSON的例子.

首先在JSON官方网站提供的一个开源的JSON解析器和字符串转换器:json.js.

根据json.js解释文档可以知道:

        array.toJSONString(whitelist)
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString(whitelist)
        string.toJSONString()

   上面6个函数可以产出json文本,这不必包括任何周期性参数,非法值会被排除.date的缺省转换是一个ISO字符串.你能够添加toJSONString()函数到任何date对象来获得不同的呈现.object和array函数包含whitelist参数选项,whitelist是一个字符串数组,如果它被提供的话,那么在whitelist中没有找到在Objects的keys会被排除.

   string.parseJSON(filter)这个函数解释json文本来产生对象和数组,它能够抛出语法错误的异常.选项filter参数具有过滤和转换结果的功能,它能够接受每一个键和值,它能够返回被使用的值代替原来的值.如果它返回接收的东西,那么结构会被修改,如果返回undefined(未定义)的话,则成员会被删除.

  例子:

  //解释文本,如果键包含字符串为'date',那么转换该值为日期.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

   下面是一个将数组转换为对应json串的例子:

//事先包含json.js
function toJSONExample(){
 var jNBtn=document.getElementById("jN");
 jNBtn.onclick=function(){
   var continents=new Array();
   continents.push("Europe");//添加元素到数组
      continents.push("Asia");
      continents.push("Australia");
      continents.push("Antarctica");
      continents.push("North America");
      continents.push("South America");
      continents.push("Africa");
   alert("continents数组的JSON呈现是: " +
 continents.toJSONString());
 }
 
 
}

结果:

["Europe","Asia","Australia","Antarctica","North America","South America","Africa"]
 
 
下面是一个将原来生成的json串转换成数组,在这里需要一个eval函数来解释json串,eval函数用来接收一个校验javascript代码的输入字符串,以下的代码经常需要将json文本转换为原来的面貌.
               var value = eval( "(" + jsonText + ")" );
 
例子:
 
function toPaseJSONExample(){
  var jNBtn=document.getElementById("jN");
 jNBtn.onclick=function(){
  var ArrayAsJSONText='["Europe","Asia","Australia","Antarctica","North America","South America","Africa"]';
  var continents=eval(ArrayAsJSONText);//校验ArrayAsJSONText数组
    var continents = ArrayAsJSONText.parseJSON();
  document.getElementById("jsonRespose").innerHTML=continents;
  }
 }
 
结果:
  Europe,Asia,Australia,Antarctica,North America,South America,Africa
 
总结:
在这里,我只是简单的介绍了JSON在客户端的应用,toJSONString()以及parseJSON()的使用方法.至于服务器端(ASP,ASP.NET)如何解释JSON和使用JSON传送数据以及运用AJAX和JSON来传输数据的应用,我会在以后的日子里再作介绍.

posted on 2009-05-24 17:36  天涯之外  阅读(889)  评论(0编辑  收藏  举报