如何将带有jQuery的所有元素的数组传递给PHP [英] How to pass array with all elements with jquery to php
本文介绍了如何将带有jQuery的所有元素的数组传递给PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一个数组从jQuery传递到PHP.
I am trying to pass an array from jQuery to PHP.
<input type="checkbox" id="name1" name="name[]" value="name1"> Name1
<input type="checkbox" id="name2" name="name[]" value="name2"> Name2
<input type="checkbox" id="name3" name="name[]" value="name3"> Name3<br />
<input type="checkbox" id="phone1" name="phone[]" value="samsung"> Samsung
<input type="checkbox" id="phone2" name="phone[]" value="nokia"> Nokia
<input type="checkbox" id="phone3" name="phone[]" value="motorola"> Motorola<br />
$(document).ready(function() {
$(":checkbox").on('change', function() {
var group = [];
var mygroup = {};
$(':checkbox:checked').each(function(i){
var val = this.value;
var name = this.name;
mygroup[name] = val;
var all = name + "=" + val;
group.push(all);
$.ajax({
type: "POST",
url: 'testdraft1.php',
data: mygroup, // TRIED WITH group and all also. Doesn't work.
success: function(data) {
$("#result").html(data);
}
});
});
});
});
使用此代码,将数组传递给PHP,但只有1个元素.即使我选择了多个元素.我在做什么错了?
With this code the array is passed to PHP but with only 1 element. Even if I select multiple elements. What am I doing wrong?
推荐答案
这有效并且也许比使用FormData
更简单. (请注意,我已经将name[]
更改为name
,将phone[]
更改为phone
.)我还将AJAX调用移到了each
循环之外.
This works and is perhaps simpler than using FormData
. (Note that I've changed name[]
to name
and phone[]
to phone
.) I've also moved the AJAX call outside of the each
loop.
HTML:
<input type="checkbox" id="name1" name="name" value="name1"> Name1
<input type="checkbox" id="name2" name="name" value="name2"> Name2
<input type="checkbox" id="name3" name="name" value="name3"> Name3<br />
<input type="checkbox" id="phone1" name="phone" value="samsung"> Samsung
<input type="checkbox" id="phone2" name="phone" value="nokia"> Nokia
<input type="checkbox" id="phone3" name="phone" value="motorola"> Motorola<br />
JavaScript:
JavaScript:
$(document).ready(function() {
$(":checkbox").on('change', function() {
var mygroup = {};
$(':checkbox:checked').each(function(i) {
var val = this.value;
var name = this.name;
mygroup[name] = (mygroup[name] || []).concat([val]);
});
$.ajax({
type: "POST",
url: 'testdraft1.php',
data: mygroup,
success: function(data) {
$("#result").html(data);
}
});
});
});
编辑
此行有点令人困惑:
mygroup[name] = (mygroup[name] || []).concat([val]);
这是它的一个简单版本:
Here's a simpler version of it:
// initialize with an empty array if needed
if (mygroup[name] === undefined) {
mygroup[name] = [];
}
// append the most recent value to the array
mygroup[name].push(val);
这篇关于如何将带有jQuery的所有元素的数组传递给PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文