Why does jQuery ajax call only work when I'm debugging in Chrome?

后端 未结 2 1903
醉酒成梦
醉酒成梦 2021-01-14 03:40

I have a simple ajax call from a form submit. It works when I debug, i.e the alert pops up but when running it, it doesn\'t work?

This seems a bit mysterious to me.<

相关标签:
2条回答
  • 2021-01-14 04:30

    Check in case if you have wrote console.log by chance in your method

    0 讨论(0)
  • 2021-01-14 04:35

    If you run an ajax call on the .submit() handler of a form, the Ajax request will fire but then the form will continue submitting, thus refreshing the page and never firing your callback function.

    Instead, you should call event.preventDefault() at the end of the submit handler function to prevent the browser from submitting the form normally with a new HTTP request. To do this you'll need to add event as a parameter to the callback function, like this:

    $( "#target" ).submit(function( event ) {
      alert( "Handler for .submit() called." );
      event.preventDefault();
    });
    

    The reason it works when you debug is because everything happens slowly as you step through, without the browser submitting the form.

    0 讨论(0)
提交回复
热议问题