日期:2014-05-16  浏览次数:20324 次

jquery-json-前端组装对象

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="../js/jquery-1.7.2.js"></script>
<script src="../js/jquery.json-2.3.min.js"></script>
<script type="text/javascript" src="../js/jquery.form.js"></script>
<script>
??? function test(){
??? ??? var data = new Array();
??? ??? for (var i=1; i<3; i++){
??? ??? ??? var element = {};
??? ??? ??? element.index="arr_"+i;
??? ??? ???
??? ??? ??? var obj1 = $($("#div_"+i+">input")[0]);
??? ??? ??? var obj2 = $($("#div_"+i+">input")[1]);
??? ??? ??? var comment = {};
??? ??? ??? comment.name = obj1.val();
??? ??? ??? comment.pass = obj2.val();
??? ??? ??? element.data = comment;
??? ??? ??? data[i-1]=element;

??? ??? }
??? ??? var jsondata = $.toJSON(data);
??? ??? $("#content").val(jsondata);
??? ??? $("#myform").ajaxSubmit(function(){
??? ??? ??? $.ajax({
??? ??? ??? ??? url: 'test.php',
??? ??? ??? ??? type: 'POST',
??? ??? ??? ??? dataType: 'json',
??? ??? ??? ??? cache: false,
??? ??? ??? ??? data: $("#myform").serialize(),
??? ??? ??? ??? success: function(json) {
??? ??? ??? ??? ??? if (json != null) {
??? ??? ??? ??? ??? ??? alert(json.msg);
??? ??? ??? ??? ??? } else{
??? ??? ??? ??? ??? ??? alert('操作失败!');
??? ??? ??? ??? ??? }
??? ??? ??? ??? },
??? ??? ??? ??? error: function(e) {
??? ??? ??? ??? ??? alert(e);
??? ??? ??? ??? }
??? ??? ??? });
??? ??? ??? return false;
??? ??? });
??? ???
??? }
</script>
</head>
<body>

??? <div id="div_1">
??? ??? <input name="name_1" id="name_1" type="text" value="name1"/>
??? ??? <input name="pass_1" id="pass_1" type="text" value="pass1"/>
??? </div>
??? <div id="div_2">
??? ??? <input name="name_2" id="name_2" type="text" value="name2"/>
??? ??? <input name="pass_2" id="pass_2" type="text" value="pass2"/>
??? </div>
??? <div>
??? ??? <input type="button" value="button" onclick="test()"/>
??? </div>
??? <form id="myform" action="action.php" method="POST">
??? ??? <input type="hidden" name="data" id="content">
??? </form>
</body>
</html>