简体   繁体   English

如何在CodeIgniter中实现AJAX?

[英]How do I implement AJAX into CodeIgniter?

I am trying to understand the process of implementing AJAX Query into my CodeIgniter application. 我试图了解在我的CodeIgniter应用程序中实现AJAX查询的过程。 The goal is to a have a clickable division (button) in a view. 目标是在视图中具有可点击的部分(按钮)。 When this div is clicked the AJAX query is called and retrieves 5 movies from my DB and displays them in the view. 单击此div时,将调用AJAX查询,并从我的数据库中检索5部电影并将其显示在视图中。 Right now I have a main page with search button, this search button orders my DB by ID and then retrieves the 1st 5 movies from the DB and displays them on a new page. 现在,我有一个带有搜索按钮的主页,此搜索按钮按ID对我的数据库进行排序,然后从数据库中检索第1部5部电影,并将它们显示在新页面上。 The function I am trying to implement should retrieve the next 5 movies and replace the 1st 5 movies without reloading the page. 我尝试实现的功能应检索下5部电影并替换第1部5部电影,而无需重新加载页面。

Below is all the code I assume you should take a look at, due to its necessity. 以下是我认为您必须查看的所有代码。 Under each part of the code a short summary is provided. 在代码的每个部分下均提供了简短摘要。 And at the end I try to explain what I don't understand and what I am asking you to help with. 最后,我尝试解释我不了解的内容以及我要您帮助的内容。

Main Page - Controller xampInstallFolder/htdocs/application/obs/controllers/main.php 主页-控制器 xampInstallFolder / htdocs / application / obs / controllers / main.php

public function generate_suggestions() {

$this->db->order_by("id","desc");
$pages = $this->db->query('SELECT * FROM movies LIMIT 5');          
$data['pages'] = $pages;
$this->load->view('results_v', $data);
}

This function is called when my Search button on the main page is clicked. 单击主页上的“ Search按钮时,将调用此函数。 Right now it doesn't accept any criteria for the query it only retrieves the first 5 movies in the db. 现在,它不接受任何查询条件,仅检索数据库中的前5部电影。 Then I take the movies and store them in the pages array and load the new view with the array provided in data 然后,我拍摄电影并将它们存储在pages数组中,并使用data提供的数组加载新视图

Results Page - View *xampInstallFolder/htdocs/application/obs/views/results_v* 结果页面-查看 * xampInstallFolder / htdocs / application / obs / views / results_v *

<div id="listA">
  <table>
    <!-- Function that splits the array in $pages into the first 5 movie suggestions -->
    <?php foreach ($pages->result() as $row): ?>
      <a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
        <div id="suggested" onmouseover="" style="cursor: pointer;">
          <div id="info">  
              <p><b><?php echo $row->name ?></b></p>
          </div>
          <div class="details">
                <p><?php echo $row->summary ?></p>
          </div>
        </div    
      </a>    
    <?php endforeach; ?>
  </table>
</div>

<div id="next_btn" style="display: block;">
  <p>Click here to display next 5 movies</p>         
</div> 

I have a div listA where I display the 5 movies using a for each loop on the pages array. 我有一个div listA ,在这里我使用5用于显示pages数组上每个循环的电影。 I have much more div and information, but I was trying to keep it simple. 我有更多的div和信息,但是我试图使其保持简单。

Javascript xampInstallFolder/htdocs/ASSETS/obs/js/myscripts.js Javascript xampInstallFolder / htdocs / ASSETS / obs / js / myscripts.js

$( "#next_btn" ).click(function() {

    var xmlhttp;

    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }

    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("listA").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET","getnext5.php?q="true);
    xmlhttp.send();

});

In the head of my results view I link the javascript with this function. results视图的顶部,我将javascript与该功能链接。 It triggers when the next_btn div is clicked. 单击next_btn div时触发。 I got the code from w3schools and from what I understood you need to provide the element in which the result is displayed ( listA ) and the file where the query is stored ( getnext5.php) 我从w3schools获得了代码,据我了解,您需要提供显示结果的元素( listA )和存储查询的文件( getnext5.php)

getnext5.php Where do I put this file? getnext5.php 该文件放在哪里?

$con = mysqli_connect('localhost','root','root','obs2');
if (!$con)
  {
  die('Could not connect: ' . mysqli_error($con));
  }

mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5";

$result = mysqli_query($con,$sql);

echo "<table>";
  while($row = mysqli_fetch_array($result))
  {
          <a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
            <div id="suggested" onmouseover="" style="cursor: pointer;">
              <div id="info">  
                  <p><b><?php echo $row->name ?></b></p>
              </div>
              <div class="details">
                    <p><?php echo $row->summary ?></p>
              </div>
            </div    
  }
echo "</table>";

Here is the core function. 这是核心功能。 I tried to adjust the code from w3schools , but I am not sure if it is correct. 我尝试调整w3schools的代码,但不确定是否正确。 My DB is called obs2, but I am not sure if I should have it in both mysqli_connect and mysqli_select_db statements. 我的数据库称为obs2,但是我不确定在mysqli_connectmysqli_select_db语句中是否都应该包含它。 I also know that I have to figure out how to make it always load the next 5 movies in the list, but right now I just force it on id>5 . 我也知道我必须弄清楚如何使其始终加载列表中的下5部电影,但是现在我只是将其强制设置为id>5 And then I have the style for the $result . 然后我有$result的样式。 I think the table and `while loop are coded properly, but I don't know how to turn the divs, anchors and original php echoes into the same syntax . 我认为table和`while循环的编码正确,但是我不知道如何将div,锚和原始php echo转换为相同的语法

If you made this is far thank you very much for reading through. 如果您做到了这一点,则非常感谢您通读。 I'd say the only part I need help with is the getnext5.php . 我要说的唯一需要帮助的部分是getnext5.php Mostly the syntax. 主要是语法。 And location, where should the getnext5.php file be stored? 和位置,应该将getnext5.php文件存储在哪里? I don not think that the other parts of the code are wrong. 我认为代码的其他部分没有错。 But obviously if you spot anything in there please let me know as well. 但是很显然,如果您在此处发现任何东西,也请让我知道。 Again thanks for reading. 再次感谢您的阅读。 I'm looking forward to your replies. 期待您的答复。 If you'd need any other information just ask for it Ill add it. 如果您需要任何其他信息,请提出要求。

I only read through the last script, and I corrected some mistakes you made. 我只阅读了最后一个脚本,并且更正了您犯的一些错误。 You can put that file anywhere pretty much. 您可以将该文件放在几乎任何地方。 You can copy the code and paste it into a controller class or a views page. 您可以复制代码并将其粘贴到控制器类或视图页面中。

<?php // I just decided to start here

mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5"; # This is an integer, no quotes necessary.

$result = mysqli_query($con,$sql);

echo "<table>";

while($row = mysqli_fetch_array($result))
{ 
?> <!-- Note how we stop php right before we start printing html, since you have nested php tags throughout this block of markup -->

      <a style="display:block" href="<?=base_url('core/detail/'.$row->id)?>">
        <div id="suggested" onmouseover="" style="cursor: pointer;">
          <div id="info">  
              <p><b><?=$row->name?></b></p>
          </div>
          <div class="details">
                <p><?=$row->summary?></p> <!-- Protip, you may use <? and ?> instead of <?php and ?>. You may also use <?= as a shortcut to the "echo" function -->
          </div>
        </div>    
 <?php 
} // We are opening up our PHP tags again
echo "</table>";
?>

It seems that you're kindof all over the place with your code. 似乎您的代码到处都是。 Instead of answering your question specifically, I'm going to give you some advice as to how you can use AJAX with codeigniter much easier. 除了要专门回答您的问题外,我将为您提供一些有关如何更轻松地将AJAX与codeigniter一起使用的建议。 I'm not saying this is the best solution, but it's much more organized and clean that what you have going on. 我并不是说这是最好的解决方案,但是它可以使您进行的工作更加井井有条。 Hopefully it will point you on the right direction. 希望它将为您指明正确的方向。

Let's start from the backend and then move towards the front. 让我们从后端开始,然后向前端移动。

First, a method in a controller which queries the movies in the database. 首先,是控制器中查询数据库中电影的方法。 Notice the parameters which allow us to ask for any subset of movies, and not just the first 5. (And yes, I'm only including the important lines of code instead of everything.) 请注意,这些参数使我们可以查询电影的任何子集,而不仅仅是前5个。(是的,我仅包括重要的代码行,而不是所有内容。)

public function generate_suggestions($start = 0, $count = 5) {

    $pages = $this->db->query('SELECT * FROM movies LIMIT ' . $start . ',' . $count);

    // send back the view as a simple HTML snippet (the <table>, perhaps?)
}

Now we need some Javascript that can call this function on the server. 现在,我们需要一些可以在服务器上调用此函数的Javascript。 Since the function sends back an HTML snippet, we can just stick that snippet of html code into the page. 由于该函数会发回一个HTML代码段,因此我们可以将该HTML代码段粘贴到页面中。 JQuery makes all of this very easy, so you can avoid the complicated XMLHttpRequest stuff. jQuery使所有这些变得非常容易,因此您可以避免使用复杂的XMLHttpRequest东西。

<script type="text/javascript">
    var nextstart = 6;
    var movies_per_page = 5;

    $( "#next_btn" ).click(function() {

        // this next line makes the ajax call for us, and the inline function
        // is called when the response comes back from the server

        $.get("controller/generate_suggestions/"+nextstart+"/" + movies_per_page,
        function(data) {

            // data is what comes back from the ajax call
            // here it is the snippet of html, so let's display it as is   
            $( "#listA" ).html(data);

            nextstart += movies_per_page; // so that the next click will load the next group of movies
        });
    });
</script>

Now we just need to populate the table when the page first loads, and you can do that by calling the same ajax call on page load with a similar $.get ajax call. 现在我们只需要在页面首次加载时填充表,就可以通过在页面加载时调用与相同的$ .get ajax调用相同的ajax调用来做到这一点。

Once you understand all of this and have it working, then you should look into JSON, as it is a much better way of transferring data with ajax. 一旦理解了所有这些并使其起作用,就应该研究JSON,因为这是使用ajax传输数据的更好方法。 And jQuery makes working with JSON much easier, too. jQuery也使使用JSON更容易。

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

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