function testJson() { var jsonData = { "firstName" : "John", "lastName" : "Doe", "age" : 23 }; var employees = { "accounting" : [// accounting is an array in employees. { "firstName" : "John", // First element "lastName" : "Doe", "age" : 23 }, { "firstName" : "Mary", // Second Element "lastName" : "Smith", "age" : 32 }], // End "accounting" array. "sales" : [// Sales is another array in employees. { "firstName" : "Sally", // First Element "lastName" : "Green", "age" : 27 }, { "firstName" : "Jim", // Second Element "lastName" : "Galley", "age" : 41 }] // End "sales" Array. }// End Employees alert(employees.sales[1].firstName);// alert(employees.sales[1]["lastName"]);}
通过AJAX接收JSON数据 通过AJAX接收JSON数据有三个不同方式.委派,回调与解释. 通过委派得到JSON 这种方法没有标准命名约定,只是"委派法"倒是一个挺好的描写叙述名字,由于server创建的javascript表达式文件会把JSON分派到一个变量 中.当把server的返回文本作为參数传给eval函数时,someVar变量就会装载JSON对象,然后你就能够通过这个变量訪问. var JSONFile = "someVar = { 'color' : 'blue' }"; // example of what is received from the server.服务器返回数据演示样例 eval(JSONFile); // Execute the javascript code contained in JSONFile.运行JSONFile中的javascript代码. document.writeln(someVar.color); // 输出'blue' 通过回调得到JSON 第二个方法预先定义一个以JSON数据作为參数的函数,然后server返回的javascript表达式中调用这个函数.这种方法叫"回调法".这个方式被广泛地应用在处理第三方JSON数据中(比如,从其他域名获取的JSON数据) function processData(incommingJSON) { document.writeln(incommingJSON.color); // 输出'blue' } // example of what is received from the server... var JSONFile = "processData( { 'color' : 'blue' } )"; eval(JSONFile);