通过 Ajax 将 Javascript 对象发送到 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6937144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:50:41  来源:igfitidea点击:

Sending Javascript Object to PHP via Ajax

phpjavascriptajaxarraysjson

提问by Eric T

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

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

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.

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

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

}

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

我的问题是: 我可以在这个函数中放入什么来将数组拉入我试图调用的 php 脚本 ('create_amenities.php')?

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

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

Thanks in advance.

提前致谢。

回答by jantimon

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

如果您的数组有超过 1 个维度或者是一个关联数组,您应该使用 JSON。

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 把一个完整的数组结构变成了一个字符串。这个字符串可以很容易地发送到你的 php 应用程序并转换回一个 php 数组。

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

有关 json 的更多信息:http: //www.json.org/js.html

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

In php you can decode the string with json_decode:

在 php 中,您可以使用 json_decode 解码字符串:

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

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

var_dump(json_decode($json));

回答by Quentin

Loop over the array and append encodeURIComponent('keyname[]') + '=' + encodeURIComponent(theArray[i]) + '&'to the query string each time.

循环遍历数组并encodeURIComponent('keyname[]') + '=' + encodeURIComponent(theArray[i]) + '&'每次附加到查询字符串。

furthermore, should I try using JSON?

此外,我应该尝试使用 JSON 吗?

You could, but it would mean decoding JSON at the other end instead of letting normal form handling take care of it.

你可以,但这意味着在另一端解码 JSON 而不是让正常的表单处理来处理它。

And if so, how could I send a JSON object via ajax?

如果是这样,我如何通过 ajax 发送 JSON 对象?

There is no such thing as a JSON object. JSON takes the form of a string, and you can include strings in query strings (just remember to encodeURIComponent).

一个JSON对象没有这样的事情。JSON 采用字符串的形式,您可以在查询字符串中包含字符串(请记住encodeURIComponent)。

回答by KateYoak

First off, yes, do not write ajax by hand. You are unlikely to produce something that truly works on all browsers.

首先,是的,不要手动编写 ajax。你不太可能产生真正适用于所有浏览器的东西。

The best approach to your actual problem would be to submit your array as cgi parameters.

解决实际问题的最佳方法是将数组作为 cgi 参数提交。

If the checkboxes are in a form, you need to do very little - simply submit the form,

如果复选框在表单中,您只需要做很少的事情 - 只需提交表单,

 <form><input type=checkbox ...><input type=checkbox ...>
 $.post("test.php", $("#testform").serialize());

See http://api.jquery.com/jQuery.post/for more details on how to do that. Your list will turn up as an array in PHP.

有关 如何执行此操作的更多详细信息,请参阅http://api.jquery.com/jQuery.post/。您的列表将在 PHP 中显示为数组。

Or to augment your own example with something very simple, do this:

或者用一些非常简单的东西来增强你自己的例子,这样做:

  url = url + '?checkboxes=' + checkboxes.join(',');

Now just split it inside PHP and you've got it back!

现在只需将它拆分到 PHP 中,您就可以找回它了!