Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

jquery - Ajax Form submit with preventDefault

I have a normal HTML form in which it is supposed to prevent default form submit and post the values by Ajax. It is not working with my setup Please help me where I went wrong. See me as Novice in Jquery,javascrip

 <link rel="stylesheet" type="text/css" href="./jQuery MultiSelect Widget Demo_files/jquery.multiselect.css">

<link rel="stylesheet" type="text/css" href="./jQuery MultiSelect Widget Demo_files/jquery-ui.css">
<script type="text/javascript" src="./jQuery MultiSelect Widget Demo_files/jquery.js">     </script>
<script type="text/javascript" src="./jQuery MultiSelect Widget Demo_files/jquery.form.js"></script>
<script type="text/javascript" src="./jQuery MultiSelect Widget Demo_files/jquery-ui.min.js"></script>
<script type="text/javascript" src="./jQuery MultiSelect Widget Demo_files/jquery.multiselect.js"></script>
<script type="text/javascript">
    $(function(){

       $("select").multiselect({
          selectedList: 4
       });

    });
</script>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (ev) {
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
            alert('ok');
        }
    });

    ev.preventDefault();
});

My Form looks like

<form action=index1.php id="contactForm1" method="post">
<p>
    <select name="example-list[]" multiple="multiple" style="width: 400px; display: none;">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
    <option value="option4">Option 4</option>

    </select>
</p>
<input class="text"  type="submit"  value='GO'>
 </form>
 </body>
 </html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Wrap your code in DOM Ready

$(function () {
    var frm = $('#contactForm1');
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                alert('ok');
            }
        });
        ev.preventDefault();
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...