使用 JSON 将 Javascript 数组传递给 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13347745/
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
Using JSON to pass Javascript array to PHP
提问by Jorg Ancrath
I have 2 selects on my HTML, the options are loaded via my database and the user can switch the options between the boxes, like so:
我的 HTML 上有 2 个选择,选项通过我的数据库加载,用户可以在框之间切换选项,如下所示:
<select id="column1" multiple size="10" name="FromLB" style="width:150px">
<?php foreach ($result->result() as $row) { ?>
<option value="<?php echo $row->id ?>"><?php echo $row->title ?></option>
<?php } ?>
</select>
So far so good, the final plan is for the the user to click Submit and to have access to the data on these two selects in PHP (via an array).
到目前为止一切顺利,最终计划是让用户单击提交并在 PHP 中访问这两个选择的数据(通过数组)。
After digging around for a bit, it seems like JSON is the way to go.
仔细研究了一下之后,似乎 JSON 是要走的路。
I import json.js to my project and get to work:
我将 json.js 导入我的项目并开始工作:
function sort_cols(){
var i=0;
var p=0;
var column1 = new Array();
var column2 = new Array();
$("#column1 option").each(function()
{
column1[i]=$(this).val();
i=i+1;
});
$("#column2 option").each(function()
{
column2[p]=$(this).val();
p=p+1;
});
JSON = JSON.stringify(column1);
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: JSON,
success: function(){
alert("Success!")
}
});
}
So far I'm only passing one array (for the first select column), but I'm getting an error: Uncaught TypeError: Object ["15","14","1"] has no method 'stringify'
到目前为止,我只传递一个数组(对于第一个选择列),但我收到一个错误:未捕获的类型错误 :对象 ["15","14","1"] 没有方法 'stringify'
I've been following this answer: How exactly do you use json_decode to pass a javascript array to php?
我一直在关注这个答案: 你究竟如何使用 json_decode 将 javascript 数组传递给 php?
I'm wondering what am I doing wrong here, and how can I pass my second array (column2) as well?
我想知道我在这里做错了什么,以及如何传递我的第二个数组(column2)?
回答by Sirko
In this line
在这一行
JSON = JSON.stringify(column1);
you redefine the native JSON object. Use another name for your variable and you should be fine.
您重新定义本机 JSON 对象。为您的变量使用另一个名称,您应该没问题。
And as for submitting both arrays, just use an encapsulating object:
至于提交两个数组,只需使用一个封装对象:
data2send = JSON.stringify( { 'column1': column1, 'column2': column2 } );
Besides instead of using an incrementing index to insert your data into the arrays, just use the native push()
method.
除了使用递增索引将数据插入数组之外,只需使用本机push()
方法。
回答by Kelvin
There's some strange behaviour happening here, most likely caused by the fact your JSON
variable is overwriting the browser's native JSON
object (or the one provided by json.js
in older browsers).
这里发生了一些奇怪的行为,很可能是因为您的JSON
变量覆盖了浏览器的本机JSON
对象(或json.js
旧浏览器中提供的对象)。
You can actually pass an object directly to $.ajax
, so the following will work:
您实际上可以将对象直接传递给$.ajax
,因此以下内容将起作用:
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: column1,
success: function(){
alert("Success!")
}
});
If you want to pass both columns as separate parameters, change it to:
如果要将两列作为单独的参数传递,请将其更改为:
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: {
first_column: column1,
second_column: column2
},
success: function(){
alert("Success!")
}
});
They will now be available in your PHP script as $_POST['first_column']
and $_POST['second_column']
.
它们现在将在您的 PHP 脚本中以$_POST['first_column']
和 的形式提供$_POST['second_column']
。
This way, you leave the heavy lifting of converting your objects to JSON to jQuery, so you don't need to include the json.js
library at all.
通过这种方式,您可以完成将对象转换为 JSON 到 jQuery 的繁重工作,因此您根本不需要包含该json.js
库。
Your full code, rewritten:
你的完整代码,重写:
function sort_cols(){
var column1 = [],
column2 = [];
$("#column1 option").each(function() {
column1.push($(this).val());
});
$("#column2 option").each(function() {
column2.push($(this).val());
});
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: {
first_column: column1,
second_column: column2
},
success: function(){
alert("Success!")
}
});
}
回答by SReject
Make jQuery do the heavy lifting:
让 jQuery 完成繁重的工作:
function sort_cols(){
var col1 = [], col2 = [];
$("#column1 option").each(function() {
col1.push($(this).val());
});
$("#column2 option").each(function() {
col2.push($(this).val());
});
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
contentType: "application/json",
data: JSON.stringify({
column1: col1,
column2: col2
}),
success: function(){
alert("Success!")
}
});
}