Jquery将键/值配对数组发送到PHP

说实话,我不知道如何构建这个问题,但是这里有。

我有一个包含以下输入字段的表单:

   

我可以使用Jquery创建一个数组,发送到PHP脚本,如下所示:

  var new_keys = new Array(); $('input[name="keys[]"]').each(function() { new_keys.push($(this).attr('value')); }); 

但是,当输入字段已经有一个键时,我不知道如何创建数组: input name =“test [45]”

我尝试将我的方法更改为使用类选择器而不是输入名称,但我无法获取键名。

我需要做的是将keyname及其值发送给PHP,这样我就可以更新keyname等于表ID号的表。 如果我不使用Ajax,这很容易做到。

希望有道理。

编辑

 
$(document).ready(function() { $.fn.submitForm = function() { var name = $('#name').attr('value'); var new_keys = new Array(); $('input[name="keys[]"]').each(function() { new_keys.push($(this).attr('value')); }); $.ajax({ type: 'POST', data: { 'new_keywords' : new_keywords, 'name' : name }, dataType: 'json', url: 'article/scripts/article.scripts.php', success: function($data) { var result = $data.result; var msg = $data.msg; if (result == "success") { formMessageDisplay(msg, result); } else { formMessageDisplay(msg, result); } }, error: function($data) { formMessageDisplay('', result); } }) } });

这是我的脚本的缩减版本。

你可以做这样的事情,它应该获取字段的名称,然后在数组中分配值。 然后,您可以根据需要在PHP中处理和清理它:

 var new_keys = new Array(); $('input[name="keys[]"]').each(function() { new_keys[$(this).attr('name')] = $(this).attr('value'); }); $.post('url/to/script/here.php', new_keys, function(data) { // process data here on success }, 'json'); // expecting a json object 

有关使用post方法http://api.jquery.com/jQuery.post/进一步阅读ajax look @ this

您可以尝试将值作为数组传递,将名称作为另一个数组传递,然后在PHP array_combine()它们与array_combine()结合使用,如下所示:

 var new_keys = new Array(); var new_names = new Array(); $('input[name="keys[]"]').each(function() { new_keys.push($(this).attr('value')); new_names.push($(this).attr('name')); }); //Then in PHP $complete_array = array_combine($new_names, $new_keys); 

只是为了澄清你有一个表单,你想通过javascript / ajax将值发送到php脚本?

如果是这样,那么你会有类似的东西:

HTML:

 
... ...

使用Javascript / jQuery的:

  $('form').bind('submit', function() { $.ajax({ url: 'phpScript/location', data: $('form').serialize(), // This will give you the needed key/pair parameterization you need. type: 'POST', dataType: 'html', // This can be one of many values. Just defines the expected response type. success: function(data, status, xhr) { // Success response }, }); return false; }); 

在此处序列化文档: http : //api.jquery.com/serialize/