2011-04-02 132 views
0

我有一頁完整的以_off.jpg結尾的圖像。我有一個onclick事件,點擊圖像時,它會將圖像更改爲圖像的_on.jpg版本(灰色圖像)。這部分工作正常。我也希望它調用一個update.php頁面,我將使用傳入的圖像被點擊的變量來更新數據庫。如何通過onclick事件獲取並傳遞變量以更新數據庫

問題是我無法獲取單擊圖像的變量以傳遞到update.php頁面。

這裏是jQuery函數交換每個圖像與Ajax調用update.php

jQuery(function(){ 
      $(".img-swap").live('click', function() { 
       if ($(this).attr("class") == "img-swap") { 
       this.src = this.src.replace("_off","_on") 
        $.ajax({ 
        type: "get", 
        url: "updatelist.php" 
        }); 
      } else { 
       this.src = this.src.replace("_on","_off"); 
       } 
       $(this).toggleClass("on"); 
      }); 
    }); 

這裏是從目錄中調用圖像

  $files = glob("movieposters/*_off.*"); 
      for ($i=0; $i<count($files); $i++) 
      { $num = $files[$i]; 
      echo '<img src="'.$num.'" border="3" style="border-color:#ffffff" class="img-swap">'; 
+0

什麼是您的GET請求到PHP FIL è?現在,它完全是空白的。 – Blender 2011-04-02 18:38:48

+0

這就是我的知識缺乏,我想它是被點擊的圖像名稱,但不知道如何做到這一點 – 2011-04-02 18:51:40

回答

0

我認爲這會做你想要什麼......

顯示圖像

<?php 
    // Load list 
    $_fileList = glob("movieposters/*_off.*"); 

    foreach ($_fileList as $_file) 
     echo '<img src="' . $_file . '" border="3" style="border-color:#ffffff" class="img-swap">'; 
?> 

交換他們......

<script> 
$(function(){ 
    $('.img-swap').live('click', function() { 
     var _src = $(this).attr('src'); 
     if (-1 == _src.indexOf('_on')) { 
      $(this).attr('src',_src.replace('_on','_off')).removeClass('on'); 
     } else { 
      $(this).attr('src',_src.replace('_off','_on')).addClass('on'); 
     } 

     // Update server 
     $.get('updatelist.php?image='+escape(_src)); 
    }); 
}); 
</script> 

那麼你的服務器腳本(updatelist.php):

<?php 
    $_clickedFile = $_GET['image']; 
    ... 
?> 
+0

謝謝,這就像一個魅力 – 2011-04-02 20:19:15

+0

隨時隨地!樂意效勞。 – lucifurious 2011-04-02 20:20:14

0

這裏有一個部分AJAX請求的快速示例:

$.ajax({ 
    type: "GET", 
    url: "file.php", 
    data: "foo=three&bar=asdfg", 
    success: function(data) { 
    alert('Response was: ' + data); 
    } 
}); 

將變量設置爲派就在這裏,"foo=three&bar=asdfg",所以如果你要發送的圖像的src=,這種要求可能的工作:

$.ajax({ 
    type: "GET", 
    url: "file.php", 
    data: "name=" + encode($(this).attr('src')), 
    success: function(data) { 
    alert('Response was: ' + data); 
    } 
}); 

請注意,我用encode()。您需要需要來編碼您的請求。

+0

我改變了我原來的ajax來添加你的建議,但似乎無法得到它上班。也許我有我的代碼錯誤在接收更新數據庫的PHP文件中的數據。我把它當作「$ film = $ _ get ['name'];」它是否正確? – 2011-04-02 19:29:01