根据AJAX成功更改img属性(src,alt ...)(并修复我的ajax;)) [英] Change img properties (src, alt...) based on AJAX success (and fix my ajax ;) )

查看:48
本文介绍了根据AJAX成功更改img属性(src,alt ...)(并修复我的ajax;))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的图片链接:

The image link I'm using:

echo "<br/><div class='right' id='post" . $id . "'>
<img id='thumb' src='/images/like.png' title='Like it?' alt='Like button' 
          onClick='likeButton(" . $id . ");'>( " . getLikes($id) . " )</div><br/>";

JavaScript是:

and the JavaScript is:

function likeButton(id) {
    $.ajax({
        url: "../../likes/" + id, 
        type: "post", 
        data: {
            id: id},
        success: function(likes) {
        $('#post' + id).html(likes);
    }}); 
}

"likes"是将点击添加到数据库的PHP函数,它还返回数字( getLikes($ id)).

"likes" is the PHP function that adds the click to the db, and it also returns the number (getLikes($id)).

但是这里有几处错误.单击后,图像消失,只剩下数字

But there's a couple things wrong here. When I click, the image disappears and I'm only left with the number

相反,我需要它来继续显示图像(以及数字周围的括号)-但是如果PHP函数 getLikes($ id)=="true" ,则更改图像src和alt.

Instead, I need it to keep showing the image (and the paranthesis around the number) - but change the image src and alt if the PHP function getLikes($id) == "true".

有没有人?

推荐答案

代替替换ENTIRE帖子的内容,只需更改likes的值即可:

Instead of replacing the content of the ENTIRE post, just change the value of the likes:

(.getLikes($ id).") => < span class ="likes">(.getLikes($ id).")</span>

$(`#post${id} .likes`).text(`(${likes})`);


后续问题:

您询问是否要防止多次单击.您可以添加一个标志来知道他们已经单击.

You asked about preventing clicking more than once. You can add a flag to know they have already clicked.

注意:只有这样,他们才能重新加载页面,如果您真的想阻止它们,那么这不是一个很好的解决方案.您的服务器应改为在PHP的服务器端进行阻止(例如,在按用户ID +帖子ID递增计数之前,检查它们是否已经喜欢它了.)

NOTE: This will only one until they reload the page, it's not a great solution if you really want to block them. Your server should prevent it server-side in PHP instead (e.g. check if they have already like it before incrementing the count by user id + post id).

function likeButton(id) {
    if ($('#post' + id).hasClass('already-liked')) {
        return;
    }
    $('#post' + id).addClass('already-liked');

    $.ajax({
        url: "../../likes/" + id, 
        type: "post", 
        data: {
            id: id},
        success: function(likes) {
        $('#post' + id).html(likes);
    }}); 
}

这篇关于根据AJAX成功更改img属性(src,alt ...)(并修复我的ajax;))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆