drd94483 2017-03-14 19:46
浏览 94

使用push方法和对象属性将条目从php添加到JS数组

I have a function that has to receive data from DB on Server and push it into the array. That is:

function Preload() {
  var valueToPush = {};
  var userID1 = '<?php echo $id_user;?>';
  $.ajax({

    url: 'TR.php',
    type: 'POST',
    data: {
      userID1: userID1
    },
    success: function(data) {

      var names = data
      $('#result_div_id').html(data);
      var json2 = $.parseJSON(data);
      EntriesCount = json2.length;
      $(json2).each(function(i, val) {
        $.each(val, function(k, v) {

          switch (k) {
            case 'Name':
              valueToPush.Name = v;

            case 'Phone':
              valueToPush.Phone = v;
          }
          name2.push(valueToPush);
        });
      });
      currententry = 0;
    }
  });

}
}

But this code is adding an only one entry in array. Other entries are undefined... What I am doing wrong?

  • 写回答

2条回答 默认 最新

  • duanjiu1894 2017-03-14 20:00
    关注

    I guess you are pushing to name2 on the wrong place. You should do this on the first iteration.


    Edit: after getting an example of your JSON i guess the second iteration is not needed after all. So I rewrote my final code below.

    The final code would be like this:

    function Preload() {
        var userID1 = '<?php echo $id_user;?>';
        $.ajax({
    
            url: 'TR.php',
            type: 'POST',
            data: {
                userID1: userID1
            },
            success: function(data) {
    
                var names = data;
                $('#result_div_id').html(data);
                var json2 = $.parseJSON(data);
                EntriesCount = json2.length;
                $.each(json2, function(i, val) {
                    var valueToPush = {
                        Name: val.Name,
                        Phone: val.Phone
                    };
                    // if you want to copy all values just do
                    // name2.push(val);
                    name2.push(valueToPush);
                });
                currententry = 0;
            }
        });
    
    }
    

    }

    评论

报告相同问题?