开发者

Jquery, add value to array in each loop

开发者 https://www.devze.com 2023-02-18 02:05 出处:网络
I have a jQuery app where the user can add item开发者_JAVA技巧s 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

I have a jQuery app where the user can add item开发者_JAVA技巧s 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
}


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);
      });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消