Eri*_*c T 22 javascript php arrays ajax json
我正在通过失败来学习Ajax并且遇到了障碍:
我有一个数组(如果重要的话,数组存储基于用户检查的复选框的数字ID)是用Javascript编写的.
我有一个在用户点击"保存"按钮时调用的函数.功能如下:
function createAmenities() {
if (window.XMLHttpRequest) {
//code for IE7+, Firefox, Chrome and Opera
xmlhttp = new XMLHttpRequest();
}
else {
//code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('message').innerHTML = xmlhttp.responseText;
}
}
var url = "create_amenities.php";
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是: 我可以在这个函数中添加什么来将数组拉入我试图调用的php脚本('create_amenities.php')?
此外,我应该尝试使用JSON吗?如果是这样,我怎么能通过ajax发送一个JSON对象?
提前致谢.
jan*_*mon 52
如果您的数组有多个1维或者是关联数组,则应使用JSON.
Json将完整的数组结构转换为字符串.这个字符串可以很容易地发送到您的PHP应用程序,并转回到PHP数组.
有关json的更多信息:http://www.json.org/js.html
var my_array = { ... };
var json = JSON.stringify( my_array );
Run Code Online (Sandbox Code Playgroud)
在php中你可以用json_decode解码字符串:
http://www.php.net/manual/en/function.json-decode.php
var_dump(json_decode($json));
Run Code Online (Sandbox Code Playgroud)