0

こんにちは、私は jQuery を使用するのが初めてで、Web サイトの検索機能に AJAX 関数を使用したいと考えています。ただし、関数に関連しない PHP を使用した例しか見つからないため、これを学ぶのに少し苦労しています。私は現在、この youtube の例jQuery Youtube Exampleから学ぼうとしています。ただし、これを実装するのは難しいようです。

私が達成しようとしていることについて少し。郵便番号を検索バーに入力し、AJAX を使用して一致するすべての関連データ フィールドを取得して、検索バーのすぐ下の div に表示されるようにしたいと考えています。

私は jQuery にあまり詳しくないので、これが正しい方法であるかどうかわかりませんが、どんな意見も歓迎します。前もって感謝します!

私のコードはそうです

index.php

<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<?php include("header.php"); 
$houseobject = new House();
$houseobject->search($_POST['term']);?>
<div id="mainContent">
  <div id="searchformWrap">
    <br/><h2>Search for Accomodation</h2>
    <div id="searchform"><br/><br/><br/>
      <form method="post" action="index.php" name="search" id="search_form">
        <div class="searchrow">
        <div class="searchlabel">Location</div>
        <div class="searchinput"> 
        <input type="text" name="term" id="term" />
        <input type="submit" name="submit" id="searchsubmit" value="Search"/>
      </form>
      <div class="help">e.g. 'PO5' or 'Portsmouth'</div>
    </div> <!-- end input -->
  </div> <!-- end .row -->
  <div id="searchquery"> </div>
</div> <!-- End maincontent -->

classes/class.House.inc

<?php 
include ("connect.class.Database.inc");
class House extends Database {

  public function search ($term){
    $query = "SELECT * FROM houses 
      WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
    $result = $this->mysqli->query($query);
    $num_result = $result->num_rows;
    if($num_result > 0){
      while($rows =$result->fetch_assoc()) {        
        $this->data[]=$rows;
        //print_r($rows);
      }      
      return $this->data;
    } else{
       echo 'No Records Found';    
    }
    echo json_encode($data);
  }

}

js/ajax.js

  $('input#searchsubmit').on('click', function() {
    if ($.trim(term) != '') {
       $.post('classes/class.House.inc', {term: term}, function(data) {
          $('div#searchquery').text(data);
       });
    }
  });
}

私は通常、index.php のフォームを指定して結果を取得しています...

検索.php

<table width="500" border="1" cellpadding="5">
 <tr>
  <th width="16" scope="row">id</th>
  <td width="95">bedrooms</td>
  <td width="140">description</td>
  <td width="104">roadname</td>
  <td width="71">postcode</td>
 </tr>
 <?php
 require("classes/class.House.inc");
 $obj = new House();
 if ($data = $obj->search($_POST['term']))
 {
    foreach($obj->data as $val){
      extract($val);
    }
 }
 ?>
 <tr>
      <td scope="row"><?php echo $id; ?></td>
      <td><?php echo $bedrooms; ?></td>
      <td><?php echo $description; ?></td>
      <td><?php echo $roadname; ?></td>
      <td><?php echo $postcode; ?></td>
 </tr>
</table>
4

5 に答える 5

2

コードを注意深く調べた後。対処が必要なエラーがいくつかあるようです。

  1. js は jQuery ready 関数内に含まれていません
  2. term の値が正しく取得されていません
  3. on メソッドが適切に使用されていない
  4. ajax プロパティ 'url' は小文字でなければなりません
  5. コンテンツは DOM に直接書き込まれるため、データ型は html である必要があります。
  6. 記述方法はhtml()、コンテンツが HTML である必要があります。
  7. 指しているページは PHP ページではなく、正しい検索ページではありませんでした

以下は、これらすべての問題に対する解決策です。

$(document).ready(function(){
    $('#searchsubmit').on("click", function(){
        // Get the value of the term field      
        var term = $('#term').val();
        // Proceed if the term is not empty
        if($.trim(term)!=''){           
            // Load the html result from the PHP script
            $.ajax({
                url: 'search.php',
                data: 'term='+term,
                type: 'POST',
                dataType: 'html',
                success: function(data){
                    // Place the HTML response into the search query div
                    $('#searchquery').html(data);
                }
            });
        }
    });
});
于 2012-11-08T12:17:41.413 に答える
0
  $("input#searchsubmit").click(function(){
    if ($.trim(term) != '') {
        $("div#searchquery").load("demo_test.txt");
    }
  });

これはうまくいくはずです..

于 2012-11-08T12:05:53.467 に答える
0

Ajax で検索するには、フォームを送信したくないので、$houseobject->search($_POST['term']);?>間違っています。Ajax 呼び出しの場合はclickorkeyupイベントを処理する必要がありますが、Ajax について話す場合は、この方がよいと思います。

たとえば、新しいファイルを作成してajax_search.php、検索した文字列 ( trim) をそのファイルに送信できます。次に、新しいファイルで新しいHouseオブジェクトを作成し、そのsearchメソッドを呼び出すことができます。

include('classes/class.House.inc');

if(isset($_POST['trim'])) {
    $house = new House();
    $json = $house->search();
    $html = '';
    // and build your HTML structure as you are doing it in search.php
    return $html;
}

Ajax 呼び出し:

$('input#searchsubmit').on('click', function() {
    var term = $('#term').val();

    if ($.trim(term) != '') {
        $.post('ajax_search.php', {term: term}, function(data) {
            $('div#searchquery').text(data);
        });
    }
});
于 2012-11-08T12:14:06.150 に答える
0

http://phery-php-ajax.netのように、それを自動的に行うライブラリを使用することができます。DOMを操作しながら、すべてが完了した後に連続して呼び出しを行うことができます。デモをチェックしてください。

あなたの場合、次のようになります(新しいデータリモートに注意してください。フォームが自動的にAJAX化されます):

 <form method="post" action="index.php" data-remote="search" name="search" id="search_form">
    <div class="searchrow">
    <div class="searchlabel">Location</div>
    <div class="searchinput"> 
    <input type="text" name="term" id="term" />
    <input type="submit" name="submit" id="searchsubmit" value="Search"/>
  </form>

Houseクラス内:

class House extends Database {

   public function search ($term){
      $query = "SELECT * FROM houses 
      WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
      $result = $this->mysqli->query($query);
      $num_result = $result->num_rows;

      if ($num_result > 0){
        while($rows =$result->fetch_assoc()) {        
           $this->data[]=$rows;
        }      
        return $this->data;
      } 

      return false;
  }

  function ajax_search($data){ // $data got the 'term' key
    $r = new PheryResponse('#searchquery'); // select where to put the results
    $data = $this->search($data['term']);

    if ($data !== false){ // got results
      $table = new PheryResponse('<table/>', array(
        'width' => "500",
        'border' => "1",
        'cellpadding' => "5"
      ));

      $html = <<<HTML
<th width="16" scope="row">id</th>
  <td width="95">bedrooms</td>
  <td width="140">description</td>
  <td width="104">roadname</td>
  <td width="71">postcode</td>
</tr>
HTML;
      foreach ($data as $row)
      {
         $html .= <<<"HTML"
<tr>
  <td>{$row['id']}</td>
  <td>{$row['bedrooms']}</td>
  <td>{$row['description']}</td>
  <td>{$row['roadname']}</td>
  <td>{$row['postcode']}</td>
</tr>
HTML;
      }
      $table->html($html); // Set the html() of the table
      $r->html($table); // Add table to the #searchquery div
    }
    else
    {
      $r->text('No results found');
    }
    return $r; // return your answer
  }
}

コントローラーには次のものがあります。

$house = new House;

Phery::instance()->set(array(
  'search' => array($house, 'ajax_search')
))->process();

それだけです。DIV にはデータベースからの新しいデータが含まれます。

于 2012-11-12T02:54:12.603 に答える
0

これは、keyup イベントをトラップし、型指定された値を取得する jQuery コードになります。

$('#searchBox').on('keyup', function() {
    var term = $('#term').val();
    if ($.trim(term) != '') {
        $.ajax({
            URL:'classes/class.House.inc', 
            data: 'term='+term,
            dataType :'json',
            success : function(text) {
                var strSrch = '';
                $.each(arr, function(k,v) {
                    var strSrch += '<td>'+v+'</td>'; //or whatever HTML you have
                });
                $('div#searchquery').text(strSrch);
            }
        });
    }
});

次に、PHP ファイルでクラスのオブジェクトを作成し、検索関数を呼び出します。ajax 呼び出しが行われた場合。

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {//this will check if it is an ajax call.
if(isset($_REQUEST['term']) && trim($_REQUEST['term'] !='')){
  $objHouse = new House();
  $searchResult = $objHouse->search($_REQUEST['term']);
  die($searchResult); 
}
}

これでjsonオブジェクトが得られます。これをajax呼び出し成功コールバックで使用し、デコードして検索結果グリッドを作成できます。

于 2012-11-08T12:15:08.083 に答える