1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <!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.parse()</title> <script type="text/javascript"> var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}'; var contact = JSON.parse(jsontext); document.write(contact.surname + ", " + contact.firstname + ", "+ contact.phone); var jsontext2 = {"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}; document.write("<br /><br />"+jsontext2.surname + ", " + jsontext2.firstname + ", "+ jsontext2.phone); </script> </head> <body> </body> </html>
|
输出:
Aaberg, Jesper, 555-0100,555-0120
Aaberg, Jesper, 555-0100,555-0120
前端页面接收JSON对象的实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <script> sendRecord('1'); function sendRecord(record){ var req = { user_id:<?php echo $userId;?>, record:record, } $.ajax({ url: "./a.php", type:"post", data:req, dataType:"JSON", success: function(res){ alert(Object.prototype.toString.apply(res)); if(res.result==1){ alert('11'); }else if(res.result==2){ alert('22'); }else if(res.result==3){ alert('33'); } }, error: function(){ alert('error000'); console.log(this); } }); } </script>
|
a.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <?php $record = $_POST['record']; if ($record==1) { $json['result'] = 1; }elseif($record==2){ $json['result'] = 2; }elseif($record==3){ $json['result'] = 3; } $json = json_encode($json); echo $json; ?>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <script type="text/javascript" src="./jquery.min.js"></script> <script> sendRecord('2'); function sendRecord(record){ var req = { record:record, } $.ajax({ url: "./b.php", type:"post", data:req, dataType:"JSON", success: function(res){ alert(Object.prototype.toString.apply(res)); alert(res); }, error: function(){ alert('error000'); console.log(this); } }); } </script>
|
b.php
1 2 3 4 5 6 7 8 9 10 11 12
| <?php $record = $_POST['record']; if ($record==1) { $json = array('a','aa'); }elseif($record==2){ $json = array('b','bb'); }elseif($record==3){ $json = array('c','cc'); } $json = json_encode($json); echo $json; ?>
|
总结:如果后台是通过echo json_encode();
输出json字符串的话,而且前台使用了dataType:"JSON"
, 那么则不需要JSON.parse();
把json字符串转换成对象或数组。
另外:把原来是对象的类型转换成字符串类型(或者更确切的说是json类型)使用函数JSON.stringify。