2015-02-24 74 views
2

我有一个文本框的表单。这个表单使用ajax提交。提交时,我想将文本字段中的数据保存在ajax变量之一中。以下是我的代码。如何将表单数据存储在ajax变量中?

<script> 
$(function() { 
//twitter bootstrap script 
$("button#submit").click(function(){ 
     $.ajax({ 

    type: "POST", 
url: "PastSurgicalCustomItem", 
data: $('form.form-horizontal').serialize(), 
     success: function(msg){ 

     var $data = $('form.form-horizontal').serialize(); 

     var $firstDiv = $('<div></div>'); 
     $firstDiv.attr("class","col-md-3"); 


     var $secondDiv = $('<div></div>'); 
     $secondDiv.attr("class","checkbox history_checkbox_div"); 
     $secondDiv.appendTo($firstDiv); 

     var $label = $('<label></label>'); 
     $label.appendTo($secondDiv); 

     var $checkBox = $('<input></input>'); 
     $checkBox.attr("type","checkbox"); 
     $checkBox.attr("class","history_checkbox"); 
     $checkBox.attr("id",msg); 
     $checkBox.appendTo($label); 

     var $span = $('<span></span>'); 
     $span.text($data); 
     $span.appendTo($label); 

     $firstDiv.appendTo($('#customDiv')); 


     }, 
error: function(){ 
alert("failure"); 
} 
     }); 
}); 
}); 
</script> 

但是,这并没有很好地工作。如果我插入数据“TEST7”,那么$data变量将包含以下

textinput=&textarea=&customName=test7 

我该如何正确的文本框里面的数据得到一个ajax变量?有关更多信息,我的应用程序使用bootstrap进行设计。

+0

存储因为使用了序列化()功能。 Plz参考这个文档http://api.jquery.com/serialize/ – 2015-02-24 11:09:07

+0

@hrs:如果我删除'serialize'然后我得到'对象' – 2015-02-24 11:11:07

+0

你想如何存储它?换句话说,你期望的输出格式是什么? – ArinCool 2015-02-24 11:13:04

回答

1

这里是你如何能得到您的表单内各个字段的值:

$('form.form-horizontal').find(':input[name="customName"]').val(); 
+0

谢谢你的回答,真的很感谢它,从我+1。 – 2015-02-24 11:24:48

1

使用serializeArray(),而不是序列化()。

serialize()输出键/值字符串textinput=&textarea=&customName=test7

serializeArray()输出JSON:

[ 
    { 
    name: "a", 
    value: "1" 
    }, 
    { 
    name: "b", 
    value: "2" 
    }, 
    { 
    name: "c", 
    value: "3" 
    }, 
    { 
    name: "d", 
    value: "4" 
    }, 
    { 
    name: "e", 
    value: "5" 
    } 
] 
+0

新的做法。 – 2015-02-24 11:25:36

3

然后你就可以在变量像这样

var variable_name= $(this).find('textarea[name="your_textarea_name"]').text(); 
+0

感谢您的回复,我真的很感激。 – 2015-02-24 11:25:05

相关问题