jQuery的关联数组的数组创建 [英] creating array of associative array in jquery
问题描述
我需要创建关联数组的数组发送相同的PHP脚本阿贾克斯职。我该怎么做呢?
要成为一个更具体一点,我有一个名为名和姓两个输入行。当我preSS提交按钮,这应该产生这样的数组:
VAR name_array = [{FIRST_NAME:字符串1,姓氏:字符串2},
{FIRST_NAME:STRING3,姓氏:串,},
。
。
]
我会再发这个数组通过AJAX后到PHP。如果上面的构造,就这样应该是什么语法发送name_array作为数据发送到PHP脚本?
<脚本SRC =https://ajax.googleapis.com/ajax/libs/jquery/1.12。 0 / jquery.min.js>< / SCRIPT>
<脚本>
$(文件)。就绪(函数()
{
变种hold_data = {};
$(文件)。在('点击','#提交',函数()
{
$(#MyForm的点域)。每个(函数()
{
hold_data [$(本).attr('名')] = $(本).VAL();
});
VAR json_data = JSON.stringify(hold_data);
警报(json_data); $阿贾克斯(
{
网址:'',// URL位置要提交数据
类型:'后',
数据:{form_data:json_data},
成功:函数(RES)
{
警报(成功发送,你的回应+ RES);
}
});
});
});
< / SCRIPT>
< /头><身体GT;
<表ID =MyForm的行动=>
名字:LT;输入类型=文本级=字段NAME =名字值=汤姆>< BR>
姓:<输入类型=文本级=字段NAME =姓氏值=夷>< BR>
<输入类型=按钮ID =提交值=提交>
< /表及GT;
< /身体GT;
柜面,如果你发布到一个PHP页面,那么你可以去code JSON数据如下图所示。
正呼应的温度值将显示为响应资源在AJAX数据
< PHP如果(使用isset($ _ POST ['form_data']))
{
$温度= json_de code($ _ POST ['form_data']);
回声温度;
}?>
I need to create an array of associative arrays for sending the same to php script as ajax post. How do I do that?
To be a little more specific, I have rows of two inputs named "First Name" and "Last Name". When I press submit button, this should generate an array like:
var name_array = [{"first_name" : string1, "last_name" : string2},
{"first_name" : string3, "last_name" : string4},
.
.
.]
I will then send this array to php through ajax post. If the above construct is made then what should be the syntax for sending name_array as data to the php script?
<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>
Incase if you are posting to a php page then you can decode the json data as shown below.
The temp value being echoed will be shown as the response res data in ajax
<?php
if(isset($_POST['form_data']))
{
$temp = json_decode($_POST['form_data']);
echo temp;
}
?>
这篇关于jQuery的关联数组的数组创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!