加入收藏 | 设为首页 | 会员中心 | 我要投稿 汽车网 (https://www.0577qiche.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP 与 js json的通信示例

发布时间:2023-07-22 09:29:49 所属栏目:PHP教程 来源:
导读:简介一下json吧,json(object notation) 是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成,它基于javascript programming language,standard ecma-262 3rd edition - december 1999的一个子集,
简介一下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['id'] = $_post['id'];  
$res['name'] = "elar";  
$res['age'] = "21";  
$response = "hello this is response".$_post['id'];  
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('show').innerhtml +=str;  
//alert(str);  
var obj = eval('('+ xmlhttp.responsetext +')');  
//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>  
<input type="button" onclick="getjson()" value="按我!"/>  
<hr />  
<div id="show"></div> 

(编辑:汽车网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章