I have a jQuery app where the user can add items to a list from an input field. I want to put all items in an array when you submit the form so I can manipulate them with php later. Is this the right way to do it?
我有一个jQuery应用程序,用户可以从输入字段向列表添加项目。当您提交表单时,我想将所有项放在一个数组中,以便稍后使用php对它们进行操作。这是正确的做法吗?
jQuery:
jQuery:
$("#form").submit(function(){
var items = [];
$("#items li").each(function(n){
items[n] = $(this).html();
});
$.post(
"process.php",
{items: items},
function(data){
$("#result").html(data);
});
});
PHP:
PHP:
$items = $_POST["items"];
foreach($items as $item){
//Something here
}
1 个解决方案
#1
13
The idea is sound. What it not very clear is that your example populates items
now, but the submit
handler will of course be called at some point in the future. Is it possible that the list items may have changed by that time?
这种想法是合理的。不太清楚的是,您的示例现在填充了项,但是提交处理程序在将来的某个时候当然会被调用。是否有可能列表项在那个时候已经改变了?
If so, you need to move the "pack the items" code inside the submit
handler, e.g.:
如果是这样,您需要将“打包项目”代码移动到提交处理程序中,例如:
$("#form").submit(function(){
var items = [];
$("#items li").each(function(n){
items[n] = $(this).html();
});
$.post(
"process.php",
{items: items},
function(data){
$("#result").html(data);
});
});
#1
13
The idea is sound. What it not very clear is that your example populates items
now, but the submit
handler will of course be called at some point in the future. Is it possible that the list items may have changed by that time?
这种想法是合理的。不太清楚的是,您的示例现在填充了项,但是提交处理程序在将来的某个时候当然会被调用。是否有可能列表项在那个时候已经改变了?
If so, you need to move the "pack the items" code inside the submit
handler, e.g.:
如果是这样,您需要将“打包项目”代码移动到提交处理程序中,例如:
$("#form").submit(function(){
var items = [];
$("#items li").each(function(n){
items[n] = $(this).html();
});
$.post(
"process.php",
{items: items},
function(data){
$("#result").html(data);
});
});