简体   繁体   English

如何将每个 php foreach 值放入每个 jquery ajax

[英]how to put each php foreach value into each jquery ajax

foreach($data['data'] as $data){
    $count = $data['number'];
}

// $data['number']; will return some number like:

159809
359107
249178
... //10+ numbers

Then, how to put each php foreach value into each jquery ajax ?那么,如何将每个 php foreach 值放入每个jquery ajax (put every number via a jquery ajax, there will be 10+ ajax calls, and return all the data in one div). (通过 jquery ajax 输入每个数字,将有 10+ ajax 调用,并在一个 div 中返回所有数据)。 Thanks.谢谢。

<script type="text/javascript">
jQuery(document).ready(function(){
    $.ajax({
        url: "process.php", 
        dataType: "html",
        type: 'POST', 
        data: "items=<?php echo $count; ?>", //each $count value in each ajax
        success: function(data){
            $("#result").html(data);
        }
    });
});
</script>
<div id="result"></div>

put the 10 values from php array to javascript array, make a javascript loop for 10 times and call ajax function with data from javascript array. put the 10 values from php array to javascript array, make a javascript loop for 10 times and call ajax function with data from javascript array.

If you really want a unique ajax call for each $count value, with the data returning in the #result div:如果您真的想要为每个 $count 值调用一个唯一的 ajax,并在 #result div 中返回数据:

<script type="text/javascript">
    $(document).ready(function(){

<?php
foreach($data['data'] as $data){
    $count = $data['number'];
    ?>
      $.ajax({
        url: "process.php", 
        dataType: "html",
        type: 'POST', 
        data: "items=<?php echo $count; ?>",
        success: function(data){
            $("#result").append(data);
        }
      });
    <?php
}
?>

    });
</script>
<div id="result"></div>

However, I would highly recommend passing the values as an array and having only one ajax call:但是,我强烈建议将值作为数组传递,并且只有一个 ajax 调用:

$count = array();
foreach($data['data'] as $data){
    $count[] = $data['number'];
}
$datacount = implode('-',$count);
?>

<script type="text/javascript">
    $(document).ready(function(){
      $.ajax({
        url: "process.php", 
        dataType: "html",
        type: 'POST', 
        data: "items=<?php echo $datacount; ?>",
        success: function(data){
            $("#result").append(data);
        }
      });
    });
</script>
<div id="result"></div>

On the server side in process.php, you can explode('-',$_POST['items']) and then foreach through them.在 process.php 中的服务器端,您可以explode('-',$_POST['items'])然后遍历它们。

This is just one other way to accomplish it... It could be json_encoded or many other ways.这只是实现它的另一种方式......它可以是 json_encoded 或许多其他方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM