【问题标题】:How to insert data into database using a custom php MVC with ajax如何使用带有 ajax 的自定义 php MVC 将数据插入数据库
【发布时间】:2015-05-09 09:50:46
【问题描述】:

我想将数据存储到数据库中。

我试过这个:

视图中我创建了这个表单:

<form id="addControl" action="<?php echo URL ?>controles/addControl" method="POST">
    <input type="text" name="text1">
    <input type="text" name="text2">
    <input type="text" name="text3">
    <input type="submit" name="Add">
</form>

然后我创建了一个模型

controles_model.php

public function addControl(){
    $text1  = $_POST['text1'];
    $text2  = $_POST['text2'];              
    $text3  = $_POST['text3'];

    $stmt = $this->db->prepare("INSERT INTO `controles` (field1, field2, field3 ) VALUES(?,?,?)");
    $stmt->execute(array($text1,$text2,$text3));

    if($stmt == true){
        return "good";
    }else{
        return "wrong";
    }
}

然后我创建了一个控制器

controles.php

class Controles extends Controller {    
    function __construct(){
        parent::__construct();
    }
    public function index(){        
        $this->view->render('controles/index');
    }
    function addControl(){
        $this->model->addControl();
    }
}

最后,对于我创建的 JS 文件:

$("#addControl").on('submit', function(e){
    e.preventDefault();

    var url     = $(this).attr('action');
    var data    = $(this).serialize();

    $.post(url, data, function(response) {
        if(response == "good"){
            $("#insertedSuccessfully").show();
        }else if(response == "wrong"){
            $("#notInserted").show();
        }   
    });
});

这一切都行不通。我该如何解决?

注意:数据库连接正常,它工作正常,因为我可以检索 数据库中的数据。

【问题讨论】:

    标签: php ajax model-view-controller


    【解决方案1】:

    您已将事件侦听器附加到 id addControl,但您的表单的 id 为 addData。因此,您的 javascript 代码中的 var url 可能是 undefined

    并在您的 php 文件中使用 $_POST 而不是 $POST

    我还建议检查您的控制台是否有任何 javascript 错误

    【讨论】:

    • 对不起,它只是一个错误,它是 id="addControl" 不是 id="addData"
    • $_POST 不是 $POST,这里只是一个错字
    【解决方案2】:

    $POST 不是 PHP 给出的数组,更像是 $_POST。 因此,在您的模型中,您没有要插入的数据。

    【讨论】:

    • $_POST 不是 $POST,这里只是一个错字。我编辑了上面的代码
    猜你喜欢
    • 2017-08-12
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2018-05-05
    • 1970-01-01
    • 2016-12-08
    相关资源
    最近更新 更多