Heim  >  Artikel  >  php教程  >  PHP 与 js json的通信实例

PHP 与 js json的通信实例

WBOY
WBOYOriginal
2016-05-25 16:42:471210Durchsuche

简介一下json吧,json(object notation) 是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成,它基于javascript programming language,standard ecma-262 3rd edition - december 1999的一个子集,json采用完全独立于语言的文本格式,但是也使用了类似于c语言家族的习惯(包括c, c++, c#, java, javascript, perl,python等),这些特性使json成为理想的数据交换语言.

json建构于两种结构:

"名称/值"对的集合(a collection of name/value pairs),不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组(associative array).

值的有序列表(an ordered list of values),在大部分语言中,它被理解为数组(array).

php文件代码:

<?php  
    $res[&#39;id&#39;] = $_post[&#39;id&#39;];  
    $res[&#39;name&#39;] = "elar";  
    $res[&#39;age&#39;] = "21";  
    $response = "hello this is response".$_post[&#39;id&#39;];  
    echo json_encode($res);  
?>

js代码:

<script type="text/javascript">  
    function getjson() {
        var xmlhttp;
        try {
            // firefox, opera 8.0+, safari
            xmlhttp = new xmlhttprequest();
        } catch (e) {
            // internet explorer
            try {
                xmlhttp = new activexobject("msxml2.xmlhttp");
            } catch (e) {
                try {
                    xmlhttp = new activexobject("microsoft.xmlhttp");
                } catch (e) {
                    alert("您的浏览器不支持ajax!");
                    return false;
                }
            }
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readystate == 4) {
                //alert(xmlhttp.responsetext);
                var str = xmlhttp.responsetext;
                document.getelementbyid(&#39;show&#39;).innerhtml += str;
                //alert(str);
                var obj = eval(&#39;(&#39; + xmlhttp.responsetext + &#39;)&#39;);
                //var obj = eval(({"id":"123","name":"elar","age":"21"}));
                alert(obj.name);
            }
        }
        var data = "id=123";
        xmlhttp.open("post", "testjson.php", true);
        xmlhttp.setrequestheader("content-type", "application/x-www-form-urlencoded");
        xmlhttp.send("id=123");
    }
</script>

 


 

 


本文地址:

转载随意,但请附上文章地址:-)

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn