大家好,我是 jQuery 的新手,我遇到过这类问题,
我正在尝试从 jquery 创建一个数组以将其传递给 php Controller (CI)。
示例 HTML
<input type="text" acc_id="5" class="input" />
<input type="text" acc_id="10" class="input" />
<input type="text" acc_id="15" class="input" />
<input type="text" acc_id="20" class="input" />
Javascript
$('#save').click(function(){
var arrayVal = [];
$('.input').each(function(key, value){
var id = $(this).attr('acc_id');
var inputValue = $(this).val();
arrayVal[id] = inputValue;
});
$.ajax({
url: siteurl + '/sample_save',
type: 'POST',
dataType: 'json',
data: {'accounts' : arrayVal},
success: function(data) {}
});
});
这是我在 Php 中的回复
Array
(
[array] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] => value 1
[6] =>
[7] =>
[8] =>
[9] =>
[10] => value 2
[11] =>
[12] =>
[13] =>
[14] =>
[15] => value 3
[16] =>
[17] =>
[18] =>
[19] =>
[20] => value 4
)
)
请注意,响应给了我 0 - 20 之间的 key 。
但我想要这样:
Array
(
[array] => Array
(
[5] => value 1
[10] => value 2
[15] => value 3
[20] => value 4
)
)
我可以通过某种方式让它在 Php 中工作,但我想通过我的 javascript 代码更正这些东西。抱歉我的英语不好:)
最佳答案
你是对的。这显然是应该在您的 JS 代码中解决的问题。
jQuery 有一个原生的表单序列化函数。参见 here对于使用它的示例,这可能是解决您的问题的更好方法。
另请注意,javaScript 没有真正的 关联数组。您只能以与其他语言(如 PHP)中的关联数组相似的方式使用对象。
编辑
好的,在那种情况下你的代码没问题。您只需要使用对象而不是数组。
只需使用:
var arrayVal = {};
代替:
var arrayVal = [];
关于javascript - Ajax - 处理正确的数组以传递给 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24451323/