代码之家  ›  专栏  ›  技术社区  ›  tirenweb

ajax:第一步。它不指向url

  •  1
  • tirenweb  · 技术社区  · 14 年前

    我有下面的代码。我希望在提交表单后它会转到“/frontend dev.php/coche1/new”,但它永远不会去(我在相应的方法中添加了一个die(“enter”),但“enter”没有显示)。。。

    <script type="text/javascript" src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.js'></script>
    
    <script type="text/javascript">
    $(document).ready(function () {
        $('.formulario').submit(function () {
            form_data = $.param($(this).serializeArray());
            $.ajax({
                url: "/frontend_dev.php/coche1/new",
                type: "POST",
                data: form_data,
                success: function () {
                    alert("Data Saved: ");
                }
            });
        });
    });
    </script>
    
    
    <form class="formulario" id="1">
        <input type="submit" value="Save">
        <label for="coche1_marca">Marca</label>
        <input type="text" id="coche1_marca" value="FJSDF" name="coche1[marca]">  
        <label for="coche1_modelo">Modelo</label>
        <input type="text" id="coche1_modelo" value="FJSDÑF" name="coche1[modelo]">  
    </form>
    

    有什么帮助吗?

    当做

    哈维

    3 回复  |  直到 14 年前
        1
  •  3
  •   Paul Kehrer    14 年前

    你需要在你的最后有一个返回错误 .submit() 处理程序。否则它会触发AJAX,但随后也会立即提交表单,这会导致页面重新加载,因为表单本身没有任何操作。添加return false表示AJAX按预期触发。

        2
  •  2
  •   Quentin    14 年前

    你什么也没做 prevent the default action 提交表单,因此它将表单提交到action属性中指定的URL(尽管由于未能包含该强制属性,因此它将使用当前URL)。这在XHR请求返回之前发生,因此success方法从不触发。

        3
  •  1
  •   CatDadCode    14 年前

    用这个

    ...
    $('.formulario').submit(function (event)
    {
         event.preventDefault(); // This will stop the form from submitting.
         ...
         return false; // Should also stop the form from submitting, but have ran into cases where it does not. Still, include it for good measure.
    }
    

    以下是关于事件参数的一些附加注意事项:

    event.preventDefault() // Stops default actions, link redirection, form submission, etc...
    event.stopPropagation() // Stops the event from propagating up the DOM tree.
    event.stopImmediatePropagation() // Stops the current event and ALL other events on the element from propagating any further up the DOM tree.
    

    有关JQuery中事件传播的更多信息,请参见此处: http://www.c-sharpcorner.com/UploadFile/satisharveti/665/Default.aspx