How to send form data without page refresh?

前端 未结 4 753
清歌不尽
清歌不尽 2021-01-06 03:52

I have sending my data in ajax using submit button without any page refresh. But the page refreshed.

Please check my code and let me know the problem.



        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-06 04:17

    The js already prevents the form submitting

    The code in the question already prevents the form from submitting by this line:

    return false;
    

    which means: The JavaScript code in the question isn't running at all.

    The form doesn't exist yet

    The problem here is that when this line of code runs:

    $("#idForm")...
    

    that element isn't in the dom yet. As such the submit handler isn't attached to anything - when the form submits it's just a standard HTTP post request.

    To just fix the problem in the question - do one of the following

    Ensure the element exists before trying to manipulate it

    If the script runs after the element appears in the source code - the form does exist:

    ...

    Put jquery code in a document ready handler

    If the js is in a ready handler:

    
    ...
    

    It doesn't matter where the script tag is as the dom has already finished loading when it runs.

    Put all js at the end of the page

    If javascript is systematically put allat the end of the page:

    
        ...
        ...
        
    
                                     
                  
提交回复
热议问题