2010-11-18 26 views
1

我有下面的代码。我希望在提交表单后将它转到“/frontend_dev.php/coche1/new”,但它永远不会(我在相应的方法中添加了一个die(“enter”),但“enter”未显示)...jQuery.ajax:第一步。它不会去的网址

<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> 

任何帮助?

问候

哈维

+0

你可以用Firebug控制台检查它,看看AJAX呼叫是否已经结束,呼叫的状态是什么? – 2010-11-18 22:47:40

回答

3

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

+0

谢谢,我不得不去Firebug控制台看到“输入”字符串。 – ziiweb 2010-11-19 09:27:25

2

您不会对prevent the default action提交表单做任何事情,因此它会将其提交给action属性中指定的URL(尽管您未能包含该必需属性,它将使用当前URL代替)。这发生在XHR请求返回之前,所以成功方法从不会触发。

1

使用此

... 
$('.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