简体   繁体   English

如何将AJAX数据从VIEW发送到CONTROLLER? (PHP(MVC)+ AJAX)

[英]How to send AJAX data from VIEW to CONTROLLER? (PHP(MVC)+AJAX)

I have http://visiting/blog page. 我有http://visiting/blog页面。

Controller contains action_index and add_index methods. Controller包含action_index和add_index方法。 Action_index() return indexes pages. Action_index()返回索引页面。 Add_index() call model's method add_data() , which insert data from form to the database. Add_index()调用模型的方法add_data() ,它将数据从表单插入到数据库中。

I need organize my application with ajax-request, that http://visiting/blog page not to refresh after submitting the form. 我需要用ajax-request组织我的应用程序, http://visiting/blog页面在提交表单后不要刷新。

VIEW 视图

    $.ajax({
        type: 'POST',
        url: '???',   --------------------------> What should URL contain?
        data: $(this).serialize()

CONTROLLER CONTROLLER

    function action_add() {

        $title = $this->cleanStr($_POST["title_field"]);
        $text = $this->cleanStr($_POST["text_field"]);



        if ($title!="" && $text!="") {
            $this->model->add_data($title, $text);              
        } else {
            throw new Exception("Data is empty");
        }

    }

MODEL 模型

   public function add_data($title, $text) {
        try {
            $query="INSERT INTO post (title, text) VALUES('$title', '$text')";
            self::$db->query($query);
        } catch(Exception $e) {
            echo $e->getMessage();
        }
    }

VIEW 视图
It is a full html file with ajax-request. 它是一个带有ajax请求的完整html文件。 I want to handle form, that the page isn't refreshed and data is sent to the database. 我想处理表单,页面没有刷新,数据发送到数据库。

  <div class="blog">
    <h1> Blog </h1>
    <form onsubmit="return validate()" id="add_form">
        <fieldset>
            <legend>Add new post:</legend>
            <label>Title:</label><br>
            <input type="text" name="title_field" id="titlef">
            <br>
            <label>Text:</label>
            <br>
            <textarea name="text_field" id="textf"></textarea>
            <br>
            <input onclick="return validate(); return false" type="submit" value="Submit">
            <input onclick="return resetclass()" type="reset" value="Reset">
        </fieldset>
    </form>

    <div class="blogposts">
        <div id='response'></div>
        <?php
            foreach ($data as $values) {
                echo "<div class=\"blog_item\">";
                echo "<h4 class=\"blog_item_title\">" . $values["title"] . "</h4>" . 
                "<div class=\"blog_item_text\">" . $values["text"] . "</div>" .
                "<div class=\"blog_item_time\">" . $values["time"] . "</div>";
                echo "</div>";
            }
        ?>
    </div>
</div>
<script>
$(document).ready(function(){
    $('#add_form').submit(function(){

        // show that something is loading
        $('#response').html("<b style=\"font-size:20px; margin:40px;\"\">Loading ...</b>");


        $.ajax({
            type: 'POST',
            url: '???',   ------------> What should be into url?
            data: $(this).serialize()
        })
        .done(function(data){

            // show the response
            $('#response').html(data);

        })
        .fail(function() {

                // just in case posting your form failed
                alert( "Posting failed." );

        });
        // to prevent refreshing the whole page page
        return false;

    });
});
</script>

the url should be the path to your controller method you would like to hit. url应该是您想要触及的控制器方法的路径。 you do not have to include the basepath in the url (but you can if you want to). 您不必在URL中包含basepath(但如果您愿意,也可以)。 so something like: 像这样的东西:

url: "howeverYourStructureIs/Action_index",

to hit method action_index(). 命中方法action_index()。 You can think of ajax like "as if you were to hit the page, but not actually navigating to that page" kinda thing. 你可以把ajax想象成“好像你要点击页面,但实际上没有导航到那个页面”有点像。 So however you would normally hit that method, is the url you put in the ajax call. 所以你通常会遇到这个方法,就是你在ajax调用中输入的url。

hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM