2011-12-15 193 views
0

我知道這是一個非常基本的問題,但我無法確定如何在過去1小時內爬網之後修復代碼。 我有一個無序列表,其中包含有關數據庫中類別的信息,cat_id作爲主鍵。和一個以cat_id作爲外鍵的主題表,所以我想通過給定類別ID的ajax請求訪問主題表。下面是我用來生成類別的代碼。我在哪裏卡住是,我不知道它的DOM元素,以便發送的唯一ID的URL參數.. 感謝取..通過ajax傳遞參數到php

<ul id="search_form"> 
     <?php 
     $cat = Category::find_all(); 
     foreach($cat as $category) { 
      echo '<li id="'; 
      echo $category->cat_id; 
      echo '"><a href="subject.php?id='; 
      echo $category->cat_id; 
      echo'">'; 
      echo $category->category; 
      echo '</a></li>'; 

     } 

     ?> 
    </ul> 
    <div id="results"> 
     <!-- ajax contents goes here --> 
    </div> 

阿賈克斯文件

window.onload = init; 
    function init() { 
     if (ajax) { 
     if (document.getElementById('results')) { 
      document.getElementById('search_form').onclick = function() { 

      ajax.open('get', 'subject.php?id='+id); // subject.php?id= 
      // how will i pass the variable 
      ajax.onreadystatechange = function() { 
       handleResponse(ajax); 
      } 
      ajax.send(null); 
      return false; 
      } 
     } 
     } 
    } 
    function handleResponse(ajax) { 
     if (ajax.readyState == 4) { 
     if ((ajax.status == 200) || (ajax.status == 304)) { 
      var results = document.getElementById('results'); 
      results.innerHTML = ajax.responseText; 
      results.style.display = 'block'; 

     } 
     } 
    } 

和該主題.php

<?php 
    //include("tpl/header.php"); 
    include("includes/initialize.php"); 
    ?> 
     <h2></h2> 
     <?php 
      if (isset($_GET['id'])) { 
       $id= mysql_real_escape_string($_GET['id']); 
       $subject = Subject::find_subject_for_category($id); 
       foreach($subject as $subj) { 
        echo $subj->subject_title; 
       } 
      } else { 
       echo "No ID Provided"; 
      } 
     ?> 

回答

2

我已經使用jquery做這些事情,它適用於我的罰款。

$.ajax({ 
    type: GET, 
    url: "subject.php", 
    data: {id: $('#search_form :selected').val()}, 
    success: function(result){ 
    // callback function 
    } 
}); 
+0

好,我不熟悉jquery的事情..我應該呼籲成功哪個函數? – XoR 2011-12-15 21:11:17