日期:2014-05-16  浏览次数:20328 次

如何把javascript中的数组传递给PHP?
如题,请教如何把javascript的数组传递到php页面呢?这个数组的每个元素都是一个对象。

------解决方案--------------------
把对象数组转成JASON串,PHP收到后转化成JASON对象进行读取。
------解决方案--------------------
前台把JSON对象数组转化成字串:
HTML code

<script>
var zNodes =[
{ 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"}
];

function theforever_csdn(o) {
var r = [];
if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
if (typeof o == "object") {
if (!o.sort) {
for (var i in o)
r.push(i + ":" + theforever_csdn(o[i]));
if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
r.push("toString:" + o.toString.toString());
}
r = "{" + r.join() + "}";
} else {
for (var i = 0; i < o.length; i++) {
r.push(theforever_csdn(o[i]));
}
r = "[" + r.join() + "]";
}
return r;
}
return o.toString();
}

alert('json数组已经转化成字串'+theforever_csdn(zNodes)+',可以发送给后台了');
</script>

------解决方案--------------------
HTML code
<script type="text/javascript" src="http://www.coding123.net/rardownload/20110420/20110420113851756.js"></script><!--倒入json.js文件,序列化json对象用的-->
<script type="text/javascript" src="http://www.coding123.net/js/jquery.js"></script>
<script type="text/javascript">
var zNodes =[
{ 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"}
];

$.ajax({
url:'xxxx.php'//改为你的动态页
,type:'POST'
,data:{zNodes:zNodes.toJSONString()}//调用json.js类库将json对象转换为对应的JSON结构字符串
,success:function(rst){alert('PHP接收JSON数据成功!');}
,error:function(xhr){alert('PHP页面有错误!'+xhr.responseText);}
}});
</script>

------解决方案--------------------
亲,web服务端只接受字符串的参数。
要传对象就先得把对象序列化为一个字符串,最常用的就是JSON,然后服务端再对这个字符串进行反序列化,从而得到需要的对象。
------解决方案--------------------
有提交的时候,先将数据转换成json的字符串格式
JScript code

zNodes = JSON.stringify(zNodes);