2011-12-12 45 views
0

我已经搜索了数据库,但还没有真正发现任何可以回答我的问题的东西。我是新来的Ajax,所以我会尽力描述它。使用Ajax从PHP更新MySQL中的值,更改图像

我想建立一个只有两个选项的图像评级系统:接受/拒绝。 我有一个分页的画廊与10K图像,他们都需要被评为(竞争)。有一个评级(接受/拒绝)的特殊系统,然后有这个概览画廊。每个已经评分过的缩略图应显示可点击的文本/图像,例如“已接受”,具体取决于数据库值。你可以点击这个文本/图像,它会变成“拒绝”,并且mysql数据库条目也会同时改变。

左:“接受”图像的初始状态。/ 右键:更改按钮(文本或图像)和更新的数据库的值。

Example image http://shrani.si/f/2u/Gz/2y5idul/acc-rej.png

那么,什么是做最简单的方法?每个分页网站上都有上百个图片,下面有这些按钮,您必须能够来回更改值(很多时候,像只有两颗星的可编辑星级评分系统,heh)。

回答

0

至于你说的AJAX应该使用,我建议你用jQuery函数

然后查看图像应该是简单的,当你通过数据库结果 循环而循环,应先试形象价值是accpted或为了将其与关联JS功能,我将谈论后,并在该功能的Ajax请求提出,要更新该行

function change_status_image(id,status,clicked) 
{ 
    $.post("update.php",{image_id:id,image_status:status},function(data){ 
    //your callback to do something like update the value of the button 

})链接拒绝; }

这将使一个Ajax请求,将两个变量image_id和image_status在update.php你应该使用这样的事情

$q = mysql_query("UPDATE tbl_name SET column_name = '".mysql_real_escape_string($_POST['image_status'])."' WHERE image_id = '".mysql_real_escape_string($_POST['image_id'])."' "; 

有关功能使一个div或者按钮和链接的onclick ATT以change_status_image 为例

<img onclick="change_status_image(img_id,reverse_current_status)" > 
0

使用jQuery。您需要两个脚本: /rate.php /rate.js

rate.php看起来是这样的:

<?php 
    // If there are values in $_POST['edits'], then this is an ajax call. 
    // Otherwise just display the gallery 
    if ((!empty($_POST['edits']) && (count($_POST['edits']))) { 
     foreach ($_POST['edits'] as $edit) { 
      alter_image($edit); // some function to update the database 
     } 
     echo "success"; 
     exit; 
    } 

    $images = get_images(); // Some function to get the images from the database 
?> 
<?php foreach ($images as $image): ?> 
<div class="gallery-image"> 
    <img src="<?php print $image -> src ?>" /> 
    <button>Accept</button> 
    <button>Reject</button> 
    <input name="id" value="<?php print $image -> id ?>"/> 
</div> 
<?php endforeach; ?> 

rate.js看起来是这样的:

$(function() { 
    // attach click event handler to buttons 
    $('.gallery-image').on('click', 'button', function() { 
     var $this = $(this), 
      ajaxSettings = { 
       url: '', 
       type: 'post', 
       data: { 
        edits: [ 
         { 
          id: $this.parent().find('input[name=id]').val(), 
          action: $this.html() 
         } 
        ] 
       }, 
       success: function(response) { 
        if (response === 'success') { 
         // something to indicate success 
        } else { 
         // something to indicate error 
        } 
       } 
      } 
     $.ajax(ajaxSettings); 
    }) 
})