zoukankan      html  css  js  c++  java
  • 【入门】PHP 与 js的通信(via ajax,json)

    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

  • 相关阅读:
    poj 3666 Making the Grade
    poj 3186 Treats for the Cows (区间dp)
    hdu 1074 Doing Homework(状压)
    CodeForces 489C Given Length and Sum of Digits...
    CodeForces 163A Substring and Subsequence
    CodeForces 366C Dima and Salad
    CodeForces 180C Letter
    CodeForces
    hdu 2859 Phalanx
    socket接收大数据流
  • 原文地址:https://www.cnblogs.com/elaron/p/1878369.html
Copyright © 2011-2022 走看看