我正在尝试使用jQuery ajax提交帖子表格。我为此编写了一个脚本。在页面上的控制台中运行此脚本并执行成功之后(因为它成功获得Ajax的支持),但是请求参数为空之后?这怎么可能让我感到困惑,请有人帮我解决这个问题。预先感谢。
我的表格:
<form method="post" action="/foo/bar" name="foobar">
<h2>Nickname</h2>
<div style="height: 20px;"></div>
<div class="form-group">
<div class="row">
<div class="col-xs-8">
<input type="text" class="form-control" id="nickname" name="nickname" value="">
</div>
</div>
</div>
<div class="checkbox">
<input type="checkbox" name="accept" id="accept" value="1" checked="">
</div>
<div style="height: 10px;"></div>
<p>
<button class="btn btn-primary" id="voteBtn">Vote <i class="fa fa-check"></i></button>
</p>
</form>
我的脚本:
$("[name=foobar]")[0].submit(function(e) {
e.preventDefault();
var data = {
"nickname": "foobar",
"accept": 1}
$.ajax({
type: "POST",
url: "/foo/bar",
contentType: "application/x-www-form-urlencoded",
data: data,
xhr: function() {
// Get new xhr object using default factory
var xhr = jQuery.ajaxSettings.xhr();
// Copy the browser's native setRequestHeader method
var setRequestHeader = xhr.setRequestHeader;
// Replace with a wrapper
xhr.setRequestHeader = function(name, value) {
// Ignore the X-Requested-With header
if (name == 'X-Requested-With') return;
// Otherwise call the native setRequestHeader method
// Note: setRequestHeader requires its 'this' to be the xhr object,
// which is what 'this' is here when executed.
setRequestHeader.call(this, name, value);
}
// pass it on to jQuery
return xhr;
},
success: function(result) {
console.log(result);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
alert(status);
alert(error);
}
});
});
响应:
您可以使它像这样工作:
$("form .btn").on('click', function(e) {
e.preventDefault();
var data = new FormData(); //here
data.append('nickname', 'foobar');//<--
data.append('accept', 1);//<--
$.ajax({
type: "POST",
url: "/foo/bar",
//contentType: "application/x-www-form-urlencoded",//<--
data: data,
xhr: function() {
// Get new xhr object using default factory
var xhr = jQuery.ajaxSettings.xhr();
// Copy the browser's native setRequestHeader method
var setRequestHeader = xhr.setRequestHeader;
// Replace with a wrapper
xhr.setRequestHeader = function(name, value) {
// Ignore the X-Requested-With header
if (name == 'X-Requested-With') return;
// Otherwise call the native setRequestHeader method
// Note: setRequestHeader requires its 'this' to be the xhr object,
// which is what 'this' is here when executed.
setRequestHeader.call(this, name, value);
}
// pass it on to jQuery
return xhr;
},
success: function(result) {
console.log(result);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
alert(status);
alert(error);
}
});
});