【问题标题】:creating array of associative array in jquery在 jquery 中创建关联数组的数组
【发布时间】:2016-07-05 04:50:51
【问题描述】:

我需要创建一个关联数组的数组,以便将其作为 ajax 帖子发送到 php 脚本。我该怎么做?

更具体地说,我有两个输入行,分别名为“First Name”和“Last Name”。当我按下提交按钮时,这应该会生成一个数组,如:

var name_array = [{"first_name" : string1, "last_name" : string2},
 {"first_name" : string3, "last_name" : string4},
 .
 .
 .]

然后我会通过 ajax post 将此数组发送到 php。如果进行了上述构造,那么将 name_array 作为数据发送到 php 脚本的语法应该是什么?

【问题讨论】:

标签: php jquery arrays ajax


【解决方案1】:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function()
{
    var hold_data = {};
    $(document).on('click','#submit',function()
    {
        $("#myform .field").each(function()
        {
            hold_data[$(this).attr('name')] = $(this).val();
         });
        var json_data = JSON.stringify(hold_data);
        alert(json_data);

         $.ajax(
         {
             url:'', //url location for where you want to submit the data
             type:'post',
             data:{form_data:json_data},
             success:function(res)
             {
                 alert("Successfully sent and your response "+res);
              }
          });
      }); 
});
</script>
</head>

<body>
<form id="myform" action="">
  First name: <input type="text" class="field" name="FirstName"  value="Tom"><br>
  Last name: <input type="text" class="field" name="LastName" value="Raze"><br>
  <input type="button" id="submit" value="Submit">
</form>
</body>

如果您要发布到 php 页面,那么您可以解码 json 数据,如下所示。

正在回显的临时值将显示为 ajax 中的响应 res 数据

<?php

if(isset($_POST['form_data']))
{
    $temp = json_decode($_POST['form_data']);
    echo temp;
}

?>

【讨论】:

  • 非常感谢。这项工作正是我想要的方式。再次感谢威尔逊
猜你喜欢
  • 2013-11-16
  • 2015-02-03
  • 2012-04-30
  • 2021-01-22
  • 2011-03-17
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多