我想将一个简单的输入字段作为 json 数据发布到我创建的网络服务器。 现在我已经做到了:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script>
$(document).ready(function(event){
$('#postit').submit(function(){
$.ajax({
type: 'POST',
url: 'http://ihavearealurltoaserverhere',
contentType: 'application/json',
dataType: 'jsonp',
data: JSON.stringify($('#postit').serializeObject()),
complete: function() {
//called when complete
alert("DOET HET");
},
success: function(data) {
//called when successful
alert("success DOET HET " + data);
},
error: function() {
alert("DOET HET niet");
//called when there is an error
}
});
});
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
});
</script>
</head>
<body>
<form id="postit">
<input name='name' value='asd'>
<input type="submit" value="Submit">
</form>
<pre id="result">moi
</pre>
</body>
</html>
如果我现在点击提交,那么在我的网络服务中我会收到 2 个响应。 在其中一个我得到一个POST(用wireshark检查),其中我得到了正常形式的数据(如果我用CGI检查)我看到request_method = name =“asd”,其次对于AJAX帖子我收到一个GET(如我所见在wireshark中)与我的URL的剩余部分,例如,如果我发布到www.bla.com/test,那么我得到test&{name:%asd},在CGI中我在QUERY_STRING中看到这个
为什么我的 ajax 不只是将其作为普通帖子发送?
答案:
使用 e.preventDefault();
阻止表单提交。
并使用 $.post('http://example', JSON.stringify($('#postit').serializeObject()));
而不是 ajax 因为,如果您将 ajax 与 dataType 一起使用:json 来自另一个域,那么你会得到 No 'Access-Control-Allow-Origin',如果你使用 jsonp 那么它实际上不会发布,而是使用 GET,请参阅下面的答案以了解更多详细信息
最佳答案
您需要将 e.preventDefault()
添加到函数顶部,以阻止表单提交。
$('#postit').submit(function (e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://ihavearealurltoaserverhere',
contentType : 'application/json',
dataType : 'jsonp',
data : JSON.stringify($('#postit').serializeObject()),
complete : function () {
//called when complete
alert("DOET HET");
},
success : function (data) {
//called when successful
alert("success DOET HET " + data);
},
error : function () {
alert("DOET HET niet");
//called when there is an error
}
});
});
关于javascript - 如何发布ajax数据而不是标准表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32248763/