如何发布ajax数据而不是标准表单数据

时间:2015-08-27 11:58:05

标签: javascript jquery html ajax

我想将一个简单的输入字段作为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 =&#34; asd&#34;,其次为AJAX帖子我收到GET (正如我在wireshark中看到的)我的URL的其余部分,例如,如果我发布到www.bla.com/test然后我得到test&amp; {name:%asd}并且在CGI中我在QUERY_STRING中看到这个

为什么我的ajax不只是像普通邮件一样发送?

Anwser: 利用e.preventDefault();来阻止表单提交。 并使用$.post('http://example', JSON.stringify($('#postit').serializeObject()));而不是ajax,因为如果你使用ajax和dataType:来自另一个域的json那么你得到No&#39; Access-Control-Allow-Origin&#39;如果您使用jsonp,那么它实际上不会发布但使用GET,请参阅下面的答案以获取更多详细信息

1 个答案:

答案 0 :(得分:2)

您需要在功能顶部添加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
        }

    });

});