javascript中json解密

來源:互聯網
上載者:User

標籤:blog   function   json   ejs   ack   url   alert   jquery   字串   

  一直以前都會斷斷續續會碰到js中的json資料的解析,下面憑著自己的經驗,簡單的講解一下在js中的json的幾種解析方法。

 一.jquery的方式

  首先你得先得到資料,一般都是jquery的ajax請求,我們使用的方法是:

   jQuery.getJSON(url, [data], [callback])

參數說明:url:發送請求地址     data:待發送的key/value參數     callback:載入成功時回呼函數

具體請求如下:

$.getJSON("<%=request.getContextPath()%>/cityStation/queryComByCity",{"cityName":$(this).val()},function(msg){                      });

這樣從後台就會獲得一個json字串msg。

下面就將解析這個json串。

var json = jQuery.parseJSON(msg);$.each(json,function(index,item){                    alert(item.id+"==========="+index);                });

先將json串通過JQuery.parseJSON()函數解析為json對象,緊接著對json對象進行遍曆就行了。

是不是so easy!

下面說第二種:

二.原生js方法:

var json = eval(msg);for(var i=0;i<json.length;i++){                   alert(json[i].NAME);               }

跟上面的步驟一樣,都是先解析為對象,在對其進行解析。

其實還有一種很類似的方法:

msg = eval(msg);                for(var p in msg){                    alert(msg[p].id);                }

這裡不同的就是使用了foreach迴圈,是代碼看起來更簡單。

javascript中json解密

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.