首页 > 解决方案 > 尝试使用jquery发布内容时如何使用while或类似的东西来发送数据

问题描述

我有一些这样的代码:

<script>
    for(i=0;i<=5;i++){name[i]: "name",}
</script>

我知道这是错误的,因为我想使用它,但$.post我不知道该怎么做

我试过这个并且这个工作很好,但我没有在这段代码中添加一段时间,因为我不知道如何做到这一点,我会告诉你我想要的地方:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.post("demo_test_post.asp",
    {
      name: "Donald Duck",
      city: "Duckburg",
      // for(i=0;i<=5;i++){name[i]: "name",} // it's my custom data and its not working
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>

标签: javascriptjqueryhtmlforms

解决方案


我找到了这样做的方法并且它正在工作:

<script>
    var data=[];
    for(i=0;i<=5;i++){data.push(i)}
    $.post( "test.php", { 'data[]': data } );
</script>

test.php我将收到$_POST['data']一个数组,而不是像这样:

<?php
    for($i=0;$i<=count($_POST['data'])-1;$i++){
        print_r($_POST[$i]);
    }
?>

推荐阅读