【问题标题】:Echo ajax data in view在视图中回显 ajax 数据
【发布时间】:2016-03-16 10:16:58
【问题描述】:

我是 ajax 新手,我正在学习。我搜索了但我找不到解决方案。我想从我的数据库中选择所有国家并希望在表格中回显结果。我得到了结果,但我不知道如何在视图中回显它。有人请帮助我。提前致谢。

我的控制器 Ajax.php

function index()
{
    $this->load->view('Ajax/Ajax_view');
}
function Get_specific()
{
    $name=$this->input->post('name');
    $data['country']=$this->Ajax_m->select("countries");
    echo json_encode($data);
    $this->load->view('Ajax_view',json_encode($data));
}

我的模型 Ajax_m.php

function select($table){
    $query=$this->db->get($table);

    return $query->result();
}

我的视图 Ajax_view.php

<html>
<head>
                                                                                          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">    
   </script>
 <script type="text/javascript">
$(document).ready(function(){
  $('#data').hide();
    $('#sub').click(function(event){

      event.preventDefault();
      var name=$('#name').val();
      $.ajax({
         type: "POST",
         url : "<?php echo base_url(); ?>" + "index.php/Ajax/Get_specific/",
         datatype : 'html',
         data : { name: name },
         success:function(res){
 $('#data').show();
alert('done')
}      
      });  

  });
});

</script>
</head>
<body>
    <?php echo form_open('Ajax/insert'); ?>
    <input type="text" name="name" id="name" value=""><br>
    <input type="submit" name="sub" id="sub"><br>
    <?php echo form_close(); ?>
    <div id="data">
        <table>
            <tr>
                <th>name</th>
                <th>Delete</th>
            </tr>

            <?php 
            if(isset($query)):
            foreach ($query as $row): ?>
            <tr>
                <td></td>
                <td>Delete</td>
            </tr>
            <?php endforeach;
            endif;?>
        </table>
    </div>
</body>

【问题讨论】:

  • 您可以从控制器返回 html 页面(表格),然后附加它 $("#data").append(res) 或类似的东西。
  • $('#data').html(res).show();替换$('#data').show();

标签: php jquery ajax codeigniter select


【解决方案1】:
$.ajax({
     type: "POST",
     url : "<?php echo base_url(); ?>" + "index.php/Ajax/Get_specific/",
     datatype : 'html',
     data : { name: name },
     success:function(res){
    $('#data').html(res).show();
    alert('done')
}

在这里很难确切知道你想要什么,但我所做的只是成功调用 ajax,在显示之前将res 添加到元素。

编辑:如果您不想丢失元素中已有的任何内容,您可以始终使用.append() 而不是.html()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 2017-11-08
    • 2021-10-01
    • 2014-12-08
    • 1970-01-01
    相关资源
    最近更新 更多