【入門】PHP 與 js的通訊(via ajax,json)

來源:互聯網
上載者:User

JavaScript端:

注意:一定要設定xmlHttp.setRequestHeader,否則傳往PHP的參數會變成null(line 38)

亮點在line 31!

代碼

 1 <script type="text/javascript">
2 function GetJson() {
3 var xmlHttp;
4 try {
5 // Firefox, Opera 8.0+, Safari
6   xmlHttp = new XMLHttpRequest();
7 }
8 catch (e) {
9 // Internet Explorer
10   try {
11 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
12 }
13 catch (e) {
14
15 try {
16 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
17 }
18 catch (e) {
19 alert("您的瀏覽器不支援AJAX!");
20 return false;
21 }
22 }
23 }
24
25 xmlHttp.onreadystatechange = function() {
26 if (xmlHttp.readyState == 4) {
27 //alert(xmlHttp.responseText);
28 var str = xmlHttp.responseText;
29 document.getElementById('show').innerHTML +=str;
30 //alert(str);
31 var obj = eval('('+ xmlHttp.responseText +')');
32 //var obj = eval(({"id":"123","name":"elar","age":"21"}));
33 alert(obj.name);
34 }
35 }
36 var data = "id=123";
37 xmlHttp.open("POST", "testJson.php", true);
38 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
39 xmlHttp.send("id=123");
40 }
41 </script>
42 <input type="button" onclick="GetJson()" value="按我!"/>
43 <hr />
44 <div id="show"></div>

PHP端【testJson.php】:

(注意,php檔案要乾淨,<?php ?>標籤的外部不能有其他標籤,否則eval函數無法解析)

亮點在line 6

1 <?php 
2  $res['id'] = $_POST['id'];
3 $res['name'] = "elar";
4 $res['age'] = "21";
5 $response = "hello this is response".$_POST['id'];
6 echo json_encode($res);
7 ?>

總結:

js要往PHP端送資料,用的是xmlHttp.send("id=123");

PHP給js送資料,用的是echo json_encode($res);(要注意變數$res的構造應符合JSON的規範)

js要解析PHP送來的JSON格式的資料,用var obj = eval('('+ xmlHttp.responseText +')');


----------關於 json VS eval 請 --Google

聯繫我們

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