多个表单使用相同的AJAX调用具有不同的结果?

时间:2012-10-22 23:36:26

标签: php ajax jquery

如果我有许多由PHP生成的表单并希望在每个表单上都有一个“回复”按钮,它通过ajax将表单内容发送到另一个php页面,那么我可以使用相同的javascript片段进行所有这些元素?

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Reply" />
</form>

因此,如果我执行以下操作,那么我是否仍然可以单独处理所有响应并仅在单击“回复”的元素上显示响应?

$("#foo").submit(function(event){
    $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData,
        // callback handler that will be called on success
        success: function(response, textStatus, jqXHR){
            // log a message to the console
            console.log("Hooray, it worked only in the element it was clicked in!");
        });
    // prevent default posting of form
    event.preventDefault();
 });

2 个答案:

答案 0 :(得分:0)

如果您想处理页面上的所有表单,您的代码可以进行微小的更改。

$("form").submit(function(event){
    $.ajax({
        url: "/form.php",
        type: "post",
        // You have to have a way to retrieve the form data
        data: getFormData(form),
        success: function(response, textStatus, jqXHR){
            console.log("Hooray, it worked only in the element it was clicked in!");
        });
    // prevent default posting of form or just return false
    event.preventDefault();
 });

答案 1 :(得分:-1)

不,提交表单有多种方法。您可能希望将第一行更改为:

$("#replybutton").click(function(event){

然后你必须将你的回复按钮id添加到你的按钮,你必须明确列出你的ajax调用中的数据元素。此外,event.preventDefault()是不必要的。考虑一下,整个<form>标签也是不必要的。

使用表单还有其他方法可以做到这一点,但这是最简单的。