JSON進階第一篇 在PHP與javascript 中使用JSON

來源:互聯網
上載者:User
一.JSON簡介

JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式。易於人閱讀和編寫。同時也易於機器解析和產生。JSON採用完全獨立於語言的文字格式設定,但是也使用了類似於C語言家族的習慣(包括C, C++, C#, Java, JavaScript, Perl, Python等)。這些特性使JSON成為理想的資料交換語言。JSON的詳細解釋請訪問JSON官網,這個網站上有圖有真相,建議認真學習下。另外,JSON在維基百科上的介紹也很詳細,可以訪問一下。

二.PHP中JSON編碼

在PHP中產生JSON字串是非常容易的,直接使用json_encode()函數就可以將PHP資料轉換成JSON字串,此函數原形如下:

string json_encode ( mixed $value )

這個函數可以為任何資料進行轉碼,除了resource類型。

三.Javascript 解析JSON

有二種方法:一種是直接使用eval()函數。這種方法最快速。然而由於eval方法同樣可以執行任意的JavaScript代碼,因此當資料來源不可靠時則可能產生安全性問題。比如下面這個例子就會導致頁面被重新導向:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>一段使用eval()解釋會導致頁面被重新導向的JSON資料</title><script type="text/javascript" src="../jquery-1.7.min.js"></script><script type="text/javascript">//jquery通過AJAX方式得到JSON資料$(document).ready(function(){    var dangerJson = '{message:(function(){window.location=\'http://blog.csdn.net/morewindows\';})()}';    //eval(dangerJson);   //會重新導向    var jsonArray = JSON.parse(dangerJson); //會報錯 - 無效字元});</script></head><body><h1>一段使用eval()解釋會導致頁面被重新導向的JSON資料</h1></body></html>

第二種方法可以防止不安全的程式碼出現——通過瀏覽器原生支援的JSON.parse(str)方法讀取JSON資料, 該方法採用解析器驗證讀入的代碼是否真的是JSON代碼,這樣就提供了較好的安全性。但是,由於這是用類比的方式讀取,速度上會比eval()慢。

四.JSON執行個體

下面以一個執行個體來解釋資料是如何被編碼成JSON字串,JSON字串又是如何在javascript中解析使用的,程式分為json1.php及json1.html。程式還要引用Smarty、JQuery及JSON庫檔案。

1.json1.php

<?php// by MoreWindows( http://blog.csdn.net/MoreWindows )require_once ('../../smarty_libs/Smarty.class.php');  $tpl_article_array = array("001" => array("title"=>"PHP訪問MySql資料庫 初級篇", "link"=>"http://blog.csdn.net/morewindows/article/details/7102362"),"002" => array("title"=>"PHP訪問MySql資料庫 中級篇 Smarty技術", "link"=>"http://blog.csdn.net/morewindows/article/details/7094642"),"003" => array("title"=>"PHP訪問MySql資料庫 進階篇 AJAX技術", "link"=>"http://blog.csdn.net/morewindows/article/details/7086524"),);$tpl_article_json = json_encode($tpl_article_array);$tpl = new Smarty();$tpl->assign("article_array", $tpl_article_array);$tpl->assign("article_json", $tpl_article_json);$tpl->display("json1.html");?>

2.json1.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>使用json</title><script type="text/javascript" src="../jquery-1.7.min.js"></script><script type="text/javascript" src="json2.js"></script><script type="text/javascript">$(document).ready(function(){var g_jsonstr = JSON.parse('{$article_json}');//通過JSON.parse()解析JSON字串$("div").mouseenter(function(){ //mouseenter  mouseovervar thisId = $(this).attr("id");var jsonid = thisId.substring(thisId.lastIndexOf("_") + 1, thisId.length);        $("#article_link").css("position","absolute");        $("#article_link").css("left","20px");        $("#article_link").css("top",$(this).offset().top + $(this).height());$("#article_link").html("連結地址" + g_jsonstr[jsonid]['link']);$("#article_link").slideDown("fast");$(this).css("background-color","red");});$("div").mouseleave(function(){ //mouseleave  mouseout$("#article_link").hide();$(this).css("background-color","yellow");});});</script><style type="text/css">div{font-family:sans-serif;}</style></head><body>{foreach $article_array as $key=>$value}<div id="div_{$key}"><h1>{$value['title']}</h1></div>{/foreach}<p><span id="article_link" style="display:none;z-index:100"></span></p></body></html>

運行結果如下(Win7+IE9.0):

當滑鼠經過三個標題時,會觸發mouseenter事件顯示提示句。

下一篇《JSON進階第二篇AJAX方式傳遞JSON資料》將介紹如何用AJAX動態請求得到JSON資料並產生標題及提示句。

 

 

轉載請標明出處,原文地址:http://blog.csdn.net/morewindows/article/details/7197971

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.