|
|
|
|
|
本文介紹JQuery如何把JSON字符串轉(zhuǎn)為JSON對象。
下面的HTML代碼實(shí)現(xiàn)JQuery把JSON字符串轉(zhuǎn)為JSON對象。
<html>
<head>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<form id="form1">
<input type = "button" id = "demo" value = "Demo" />
<br />
<div>
Name: <input type = "text" id = "txtName" /><br />
Age: <input type = "text" id = "txtAge" /><br />
City: <input type = "text" id = "txtCity" /><br />
Country: <input type = "text" id = "txtCountry" /><br />
</div>
</form>
<script type = "text/javascript">
var json = "{Name: 'Mudassar Khan', Age: 27, City: 'Mumbai', Country: 'India'}";
$("#demo").on("click", function () {
var person = eval('(' +json + ')');
$("#txtName").val(person.Name);
$("#txtAge").val(person.Age);
$("#txtCity").val(person.City);
$("#txtCountry").val(person.Country);
});
</script>
</body>
</html>
效果如圖:
JSON字符串轉(zhuǎn)為JSON對象
解釋
在上面的代碼片段中,當(dāng)單擊HTML Demo按鈕時(shí),JSON字符串將使用javascript eval()
函數(shù)轉(zhuǎn)換為JSON對象,然后JSON對象值將顯示在各自的文本框中。