我有以下表格,我需要在提交表格时进行AJAX调用。如何通过序列化在jQuery中做到?
<form class="form-horizontal">
<fieldset>
<legend>Please Fill in the Online Form</legend>
<div class="form-group">
<label for="inputEmail" class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input type="text" class="form-control formWidth" id="inputEmail" placeholder="Name" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="reset" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
我的请求回复格式为:
http://10.23.25.36:8081/mytest/user/register
{"name":"abcd","email":"pow.122@gmail.com","phone":"12356984"}
{
"message": "SMS SENT",
"status": "SUCCESS",
}
这有什么问题?:
$(document).ready(function() {
alert("hello");
$('.form-horizontal').on('submit', function(e){
alert("inside form submit");
var postData = $(this).serialize();
var formURL = "http://10.23.25.36:8081/mytest/user/register";
$.ajax({
url : formURL,
type:"POST",
data : postData,
dataType:"json",
done:function(msg){
setSuceessMsg(msg);
},
fail:function(jqXhr, textStatus){
alert("Error in response" + textStatus);
},
always:function(msg){
alert("In always");
}
});
e.preventDefault(); //STOP default action
//e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
(function ( $ ) {
$.fn.setSuceessMsg = function(msg) {
return this;
};
}( jQuery ));
});
答案 0 :(得分:1)
您需要做的就是
var str = $( "form" ).serialize();
通过ajax调用将str发送到服务器。
Ajax语法
$.ajax({
type: "POST",
url: yourserverURL, // the method we are calling
contentType: "application/json; charset=utf-8",
data: { "YourServerMethodParameter": JSON.stringify(str),"YourServerMethodParameter2":"value" },
dataType:"json",
success: function (result) {
alert(result.responseText);
//do something
//..
//..
},
error: function (result) {
alert('Oh no aa :(' + result[0]);
}
});
<强>更新强>
您的$(“表单”)。serialize()为您提供字符串。它包含输入字段的名称和值。如果您的网络方法需要名称,电子邮件和电话的参数,那么最好单独发送它们。像
data: { "name": "value","email":"value2",... }
答案 1 :(得分:0)
这是你可以做的。
var yourdata = $("form").serialize();
$.ajax({
url: "phpfile.php",
type: "POST",
contentType: "application/json; charset=utf-8",
data: {data: yourData},
success: function(data) {
// Do stuff when the AJAX call returns
}
});