通过 Ajax 将 Javascript 对象发送到 PHP [英] Sending Javascript Object to PHP via Ajax

查看:41
本文介绍了通过 Ajax 将 Javascript 对象发送到 PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在失败中学习 Ajax 并遇到了障碍:

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

我有一个用 Javascript 编写的数组(如果重要,该数组将根据用户选中的复选框存储数字 ID).

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')?

此外,我应该尝试使用 JSON 吗?如果是这样,我如何通过 ajax 发送 JSON 对象?

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

提前致谢.

推荐答案

如果你的数组超过一维或者是一个关联数组,你应该使用 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 中,您可以使用 json_decode 对字符串进行解码:

In php you can decode the string with json_decode:

http://www.php.net/manual/en/function.json-decode.php

var_dump(json_decode($json));

这篇关于通过 Ajax 将 Javascript 对象发送到 PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆