Jquery,在每个循环中向数组添加值
我有一个 jQuery 应用程序,用户可以将项目从输入字段添加到列表中。 我想在您提交表单时将所有项目放入一个数组中,以便稍后我可以使用 php 操作它们。这是正确的做法吗?
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:
$items = $_POST["items"];
foreach($items as $item){
//Something here
}
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:
$("#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:
$items = $_POST["items"];
foreach($items as $item){
//Something here
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个想法是合理的。不太清楚的是,您的示例现在填充
items
,但是submit
处理程序当然会在将来的某个时候被调用。到那时列表项是否可能已更改?如果是这样,您需要将“打包项目”代码移至
submit
处理程序中,例如:The idea is sound. What it not very clear is that your example populates
items
now, but thesubmit
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.: