通过Ajax发送JavaScript对象到PHP

问题描述:

我在学习阿贾克斯的故障,并已碰了壁:

I'm learning Ajax by failure and have hit a wall:

我有一个数组(如果它的事项,阵列存储基于什么样的复选框用户检查人数的ID),其是用Javascript的。

I have an array (if it matters, the array is storing number id's based on what checkboxes the user checks) that is written in Javascript.

我有一个当用户点击保存按钮时调用的函数。的功能如下:

I have a function that is called when the user clicks the 'save' button. The function is as follows:

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

}

我的问题是: 我可以把这个功能拉数组复制到PHP脚本,我试图调用('create_amenities.php')?

My question is: What can I put in this function to pull the array into the php script I'm trying to call ('create_amenities.php')?

此外,我应该尝试使用JSON?如果是的话,我怎么可能通过ajax发送一个JSON对象?

furthermore, should I try using JSON? And if so, how could I send a JSON object via ajax?

在此先感谢。

如果你的阵列有更多然后1尺寸或者是一个关联数组,你应该使用JSON。

If your array has more then 1 dimension or is an associative array you should use JSON.

的Json变成一个完整的阵列结构成一个字符串。 此字符串可以很容易地发送到你的PHP应用程序,并变回一个PHP数组。

Json turns a complete array structure into a string. This string can easily send to your php application and turned back into a php array.

在JSON的更多信息: http://www.json.org/js.html

More information on json: http://www.json.org/js.html

var my_array = { ... };
var json = JSON.stringify( my_array );

在PHP中,你可以去c中的字符串json_de code $ C $:

In php you can decode the string with json_decode:

http://www.php.net/manual/en/function.json-de$c$c.php

var_dump(json_decode($json));