jquery ajax功能不起作用

Kir*_*nan 9 html ajax jquery

我的HTML就像这样,

<form name="postcontent" id="postcontent">
    <input name="postsubmit" type="submit" id="postsubmit" value="POST"/>
    <textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>
Run Code Online (Sandbox Code Playgroud)

jquery代码如下

$("#postcontent").submit(function(e) {
    $.ajax({
        type:"POST",
        url:"add_new_post.php",
        data:$("#postcontent").serialize(),
        beforeSend:function(){
            $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
        },success:function(response){   
            //alert(response);
            $("#return_update_msg").html(response); 
            $(".post_submitting").fadeOut(1000);                
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

当我单击提交按钮时,我的ajax请求不起作用,看起来好像控件正在传递给JQuery提交函数,但是ajax请求没有执行/正常工作,有什么问题?

jav*_*ker 12

将事件处理函数放在$(document).ready(function(){...})中.它现在应该工作

还添加了preventDefault()来限制页面刷新

$(document).ready(function() {

            $("#postcontent").submit(function(e) {
                e.preventDefault();
                $.ajax({
                    type : "POST",
                    url : "add_new_post.php",
                    data : $("#postcontent").serialize(),
                    beforeSend : function() {
                          $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
                    },
                    success : function(response) {
                        alert(response);
                        $("#return_update_msg").html(response);
                        $(".post_submitting").fadeOut(1000);
                    }
                });
                e.preventDefault();
            });

        });
Run Code Online (Sandbox Code Playgroud)

  • 如果这个方法行不通,为什么会被接受呢? (2认同)