Ajax;Jquery表单提交


Ajax & Jquery form submission

我要用这个把头发拔出来了。

我相信问题很简单,我是Jquery Ajax的新手,我只是忽略了一些东西。但是,伙计,这太烦人了。每次提交表单时,页面都会刷新,.ajax会抛出error:。是什么原因造成的?我确信我正在将表单值传递到Jquery。newcomment.php正在发挥作用。我可以向它发布常规表单,但不能使用jquery。

function postPhotoComment() {
    var comment = $("#comment").val();
    var album = $("#album").val();
    var photo = $("#photo").val();
    var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
    $.ajax({
        type: "POST",
        url: "/includes/actions/photo-gallery/newcomment.php",
        data: dataString,
        success: function(res) {
            alert("Posted!");
        }
            error: function(res) {
            alert("Error!");
        }
    })  
}

编辑:这是我的html表单:

<form>
    <textarea id="comment" placeholder="Post Comment..."></textarea>
    <input id="album" type="hidden" value="<?php echo "$a"?>"/>
    <input id="photo" type="hidden" value="<?php echo "$p.$ext"?>"/><br/>
    <button id="photo-comment-submit" onclick="postPhotoComment()">Post</button>
</form>

我还注意到,如果我给输入names,Chrome会像GET变量一样将它们放入url栏中。每次刷新页面后,它都会在url的末尾添加?。因此,它似乎试图定期提交表格。

是否返回false以停止浏览器的默认操作?

$('form').submit(function(){
    var dataString = $(this).serialize(); // shortcut
    $.ajax({
        type: "POST",
        url: "/includes/actions/photo-gallery/newcomment.php",
        data: dataString,
        success: function(res) {
            alert("Posted!");
        }
        error: function(res) {
             alert("Error!");
        }
    });
  return false;// cancels the default action
});

如果您调用AJAX表单提交代码的函数是表单的onSubmit方法,则需要停止默认操作,也就是说,您希望停止正常提交。

为此,请使用event对象的preventDefault方法:

function postPhotoComment(evnt) {
    evnt.preventDefault();
    // existing code continues...
}

您也可以从事件中返回false,但要注意,在不同的浏览器中这样做会产生不同的效果,而且它不像直接调用preventDefaultstopPropagation那样明确或可靠。

编辑此外,错误处理程序可能会被调用,因为您的代码启动了XHR请求,但当浏览器启动默认操作(提交表单)时,它会取消任何挂起的XHR请求。这导致错误处理程序被触发。

编辑2我创建了一个jsFiddle,并进行了工作演示:http://jsfiddle.net/wXrAU/

文档

  • MDN-上的event.preventDefault方法https://developer.mozilla.org/en/DOM/event.preventDefault

提交时请确保return false;到表单,否则它仍将作为"正常"表单提交,而不使用Ajax并重新加载页面。

编辑:看完评论后,我认为这将是最适合你的:<form action="url.php" onsubmit="return false;"></form>

jsFiddle与适当的代码:http://jsfiddle.net/SO_AMK/ZVgNv/

PHP把事情搞得有点乱,但它能正常工作。

实际上,我只是通过删除<form>标记就解决了这个问题。我根本不需要它们。但现在一切似乎都正常了。

确保您编写了一个有效的、HTTP可访问的url,而不仅仅是脚本的路径,例如

function postPhotoComment() {
    var comment = $("#comment").val();
    var album = $("#album").val();
    var photo = $("#photo").val();
    var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
    $.ajax({
        type: "POST",
        url: "http://yoursite.com/whatever/newcomment.php", // here
        data: dataString,
        success: function(res) {
            alert("Posted!");
        }
            error: function(res) {
            alert("Error!");
        }
    })  
}

因为JavaScript是一种客户端语言。它对您的文件系统结构或诸如此类的东西一无所知。AJAX请求是基于HTTP协议的。