使用 codeigniter MVC 插入到 db mysql 后立即显示数据

我有一个文本框和一个按钮,填写完文本框然后点击按钮,数据会保存到mysql。我的问题是,当我点击保存按钮时,我保存的数据的 ID 将立即出现在该页面上。我的意思是我插入mysql的数据的ID


这是视图


<label for="userAnswer">Answer</label>

<textarea name="userAnswer" id="userAnswer" class="form-control"></textarea>

<button onclick="saveAnswer()">Submit Answer</button>

这是js


function saveAnswer(){

    var inputAnswer = $('#userAnswer').val();

        $.ajax({

            type: "GET",

            url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,

            dataType: 'json',

    });

}

这是控制器


function saveAnswer(){

    $data = array(

        'id' => uuid(false),

        'answer' => $this->input->get_post("inputAnswer")

        );

        $this->db->insert('tableAnswer', $data);

}

谢谢


HUH函数
浏览 100回答 3
3回答

森栏

插入数据后,在模态中粘贴以下行&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;$this->db->insert_id();它将反映最后插入数据 ID

慕娘9325324

使用此代码:-function saveAnswer(){&nbsp; &nbsp; var inputAnswer = $('#userAnswer').val();&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "GET",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: 'json',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sucess:function(result){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert(result);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; });}结果将携带您的 id 并将显示在警报框中,并且从 ajax 返回 id 使用此代码:-function saveAnswer(){&nbsp; &nbsp; $data = array(&nbsp; &nbsp; &nbsp; &nbsp; 'id' => uuid(false),&nbsp; &nbsp; &nbsp; &nbsp; 'answer' => $this->input->get_post("inputAnswer")&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; $this->db->insert('tableAnswer', $data);&nbsp; &nbsp; &nbsp; &nbsp; $id = $this->db->insert_id;&nbsp; &nbsp; &nbsp; &nbsp; if($id > 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $id;&nbsp; &nbsp; &nbsp; &nbsp; }}如果你得到了结果,别忘了勾选它,以便其他人可以得到帮助

桃花长相依

您必须回显 id 而不是返回它才能从 Js 中获取它echo&nbsp;$this->db->insert_id();
打开App,查看更多内容
随时随地看视频慕课网APP