纯js文件中向php传送json格式数据

在.js文件中的函数输入如下
	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 user =[
	{ id:1, pId:0, name:"随意勾选 1", open:true},
	{ id:11, pId:1, name:"随意勾选 1-1", open:true},
	{ id:111, pId:11, name:"随意勾选 1-1-1"},
	{ id:112, pId:11, name:"随意勾选 1-1-2"},
	{ id:12, pId:1, name:"随意勾选 1-2", open:true},
	{ id:121, pId:12, name:"随意勾选 1-2-1"},
	{ id:122, pId:12, name:"随意勾选 1-2-2"},
	{ id:2, pId:0, name:"随意勾选 2", checked:true, open:true},
	{ id:21, pId:2, name:"随意勾选 2-1"},
	{ id:22, pId:2, name:"随意勾选 2-2", open:true},
	{ id:221, pId:22, name:"随意勾选 2-2-1", checked:true},
	{ id:222, pId:22, name:"随意勾选 2-2-2"},
	{ id:23, pId:2, name:"随意勾选 2-3"}
	];
	/*
    var user = {
		name:'大都会',
		email:'jxin@sina.com',
		password:'232555'
	}
	*/
	var json_string = JSON.stringify(user);	
	
	xmlHttp.open("POST", "action.php", true);
	xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
	var datax = "id="+json_string;
	 alert (datax);
	xmlHttp.send(datax);

在action.php中输入如下:

<?php
	
	header('Content-Type: text/html; charset=utf-8');
	$json_string = $_POST["id"];
	if(ini_get("magic_quotes_gpc")=="1")
	{
		$json_string=stripslashes($json_string);
	}
	$user = json_decode($json_string);
 
	echo var_dump($user);	

	echo '<br /><br /><br /><br />';
	echo $user[0]->id.'<br />';
	echo $user[0]->pId.'<br />';
	echo $user[0]->name.'<br />';
?>	


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值