JSON對象和JSON字串

來源:互聯網
上載者:User

標籤:style   blog   http   java   使用   資料   

<!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">//樣本1:此樣本使用 JSON.parse 將 JSON 字串轉換為對象var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';//JSON 字串var contact = JSON.parse(jsontext);document.write(contact.surname + ", " + contact.firstname + ", "+ contact.phone);//樣本2:和執行個體1是一樣的效果var jsontext2 = {"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]};//JSON 對象//var contact2 = JSON.parse(jsontext2);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對象的執行個體:

<script>sendRecord('1');function sendRecord(record){var req = {user_id:<?php echo $userId;?>,record:record,}$.ajax({url: "/3G/wall/ajax_send_record/",type:"post",data:req,dataType:"JSON", //返回資料格式為JSON對象success: function(res){if(res.result==1){  //因為傳遞過來是JSON對象,所以不用<span style="font-family:Simsun;">JSON.parse()解析</span>alert('11');}else if(res.result==2){alert('22');}else if(res.result==3){alert('33');}},error: function(){alert('error000');console.log(this);}});}</script>


<?php    function ajax_send_record()    {        $record = $_POST('record');        if ($record==1) {                    $json['result'] = 1;                    }elseif($record==2){$json['result'] = 2;}elseif(elseif($record==3){$json['result'] = 3;}$json = json_encode($json);echo $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.