[英]how to post ajax data and not standard form data
我想将一个简单的输入字段作为json数据发布到我创建的Web服务器上。 现在我已经做到了:
<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”,其次我收到一个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
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.