php json实例,PHP 与 js json的通信实例

该博客介绍了JSON(JavaScript Object Notation)作为轻量级数据交换格式的使用,它是基于ECMAScript的一个子集,易于人阅读和机器解析。文章通过PHP和JavaScript代码示例展示了如何创建JSON响应以及使用AJAX进行异步数据请求和处理。重点讲解了XMLHttpRequest对象的用法以及JSON响应的解析方法。
摘要由CSDN通过智能技术生成

选简介一下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代码

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");

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值