doujianguang5506 2016-09-17 17:23
浏览 45
已采纳

使用ajax,php和jquery形式 - 动作或不动作

a basic question from a total jquery/ajax newbie.

I have a simple form with two input fields for which I want the data passed via jquery and ajax to a php file on my server side. After processing, it should send me a nice reply back like "request was processed" or some other text.

I have searched the web and this forum and I found that not all posts/webpages/tutorials describe this in the same way. So now, I am a bit lost in the abundance of information.

First question: in all tutorials, the form is inside an .html file (like index.html). In my case, the form is in a .php file. Does this have any influence in how the form is treated. The form is written in html syntax so it should not matter if it is an .html or in a .php file, correct?

Second question:

In some tutorials, the form action will link to the php file where the data is sent. Method is usually "POST". Then, in the jquery file, the $.ajax url also points to that same php file.

Is this the correct way to do it?

If I set it up like that, upon clicking the submit button, the browser is always directed to the php file in the form-action and the jquery file I wrote is not executed. And I have no clue why this happens.

Hope someone can point me in the right direction.

  • 写回答

3条回答 默认 最新

  • doumei2023 2016-09-17 21:22
    关注

    If you have:

    <?php
    <form action="distant.php" id="myForm">
        <input type="text" name="form-element" />
        <input type="submit" value="Submit form" />
    </form>
    <div id="message"></div>
    ?>
    

    You can do this in jQuery:

    $('form').on('submit',function(e){
        e.preventDefault(); // do not try to access distant.php by reloading the page
        $.ajax({
            type     : "POST",
            url      : $(this).attr('action'), // access distant.php by ajax
            data     : $(this).serialize(), // get values from the form. In this case, only one element (with name="form-element")
            success  : function(data) {
                // response from distant.php - could be "request was processed" if you want
                $("#message").html(data); // display the response in the html
            }
        });
    });
    

    But, I don't see the point by mixing html and php.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?