ajax处理php返回json数据的实例代码
作者:
有时候我们需要ajax处理php返回的json数据,适合经常用php开发的朋友,需要的朋友可以参考下
test.html
<label onclick="javascript:post_data();">click </label>
function ajax_init()
{
var ajax=false;
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
ajax = false;
}
}
if (!ajax && typeof XMLHttpRequest!='undefined') {
ajax = new XMLHttpRequest();
}
return ajax;
}
function post_data()
{
var url = "/server/xml.php";
var show_check = document.getElementById("show_check");
var show_flag = document.getElementById("show_flag");
var ajax = ajax_init();
ajax.open("GET", url, true);
//var img = "<img src='/img/loading.gif'>";
ajax.onreadystatechange = function()
{
if (ajax.readyState == 4 && ajax.status == 200)
{
var ret = ajax.responseText;
var show_info = eval(ret);
show_check.innerHTML = show_info[0].no1; // bsd
show_flag.innerHTML = show_info[0].no2; // wuddy
//alert("responseXML's value: " + info[0].firstChild.data);
}
/*else
{
show.innerHTML = img;
}*/
}
ajax.send(null);
}
json.php
<?php
/* 这边如果写成 $info = array('no1'=>'bsd', 'no2'=>'wuddy', 'no3'=>'xie'); */
/* 同样要把html文件中必成 var show_info = eval('[' + ret + ']'); 都是返回一个对象 */
$info = array(array('no1'=>'bsd', 'no2'=>'wuddy', 'no3'=>'xie'));
$userinfo = json_encode($info);
echo $userinfo;
?>
复制代码 代码如下:
<label onclick="javascript:post_data();">click </label>
function ajax_init()
{
var ajax=false;
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
ajax = false;
}
}
if (!ajax && typeof XMLHttpRequest!='undefined') {
ajax = new XMLHttpRequest();
}
return ajax;
}
function post_data()
{
var url = "/server/xml.php";
var show_check = document.getElementById("show_check");
var show_flag = document.getElementById("show_flag");
var ajax = ajax_init();
ajax.open("GET", url, true);
//var img = "<img src='/img/loading.gif'>";
ajax.onreadystatechange = function()
{
if (ajax.readyState == 4 && ajax.status == 200)
{
var ret = ajax.responseText;
var show_info = eval(ret);
show_check.innerHTML = show_info[0].no1; // bsd
show_flag.innerHTML = show_info[0].no2; // wuddy
//alert("responseXML's value: " + info[0].firstChild.data);
}
/*else
{
show.innerHTML = img;
}*/
}
ajax.send(null);
}
json.php
复制代码 代码如下:
<?php
/* 这边如果写成 $info = array('no1'=>'bsd', 'no2'=>'wuddy', 'no3'=>'xie'); */
/* 同样要把html文件中必成 var show_info = eval('[' + ret + ']'); 都是返回一个对象 */
$info = array(array('no1'=>'bsd', 'no2'=>'wuddy', 'no3'=>'xie'));
$userinfo = json_encode($info);
echo $userinfo;
?>