jQuery unexpected refresh of page when submit an AJAX form [duplicate]

六眼飞鱼酱① 提交于 2019-12-31 05:32:05

问题


I have a problem, with AJAX submit of forms.

I have a piece of code like that:

$("#content").html("<form id='requestInfo'>............</form");

That put in a div with id=content the piece of code that creates a form.

I have another piece of code:

$("#requestInfo").submit(function( event ) {
  event.preventDefault();
  ...code...
});

I would expect an execution of the code inside the submit() method where I can do my things with data of that form, but I get a refresh of the page, instead.

Does anyone know what could be the problem? It should be compatible with all browsers.

Thanks!


回答1:


You are creating your form dynamically thus standard event binding will not work. You need to use event delegation

$("#content").on('submit', '#requestInfo', function(evt) {
    evt.preventDefault();
});



回答2:


You have to call e.preventDefault(); and return false

$("#requestInfo").submit(function( event ) {
    // Code here
    event.preventDefault();
    return false;
});


来源:https://stackoverflow.com/questions/42169053/jquery-unexpected-refresh-of-page-when-submit-an-ajax-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!