繁体   English   中英

成功调用AJAX后更新元素

[英]Update element after successful AJAX call

问题

成功调用AJAX之后,我想更新页面上的元素。 但是,它没有被更新。

代码[Javascript]

$(function()
{
    $(".upvote").click(function()
    {
        var id = $(this).parent().find("input").val();
        $.ajax(
        {
            type: "GET",
            url: "process.php",
            data: "id=" + id +"&f=u",

            success: function(results)
            {
                $(this).parent().parent().find("span.ups").empty().append("Upvotes: " + results);
                console.log(results);
            }
        });
        return false;
    });
});

代码[HTML]

这段代码是由PHP生成的。

<div class="post">
    <h2>$title</h2>
    <p>$body</p>
    <span class="ups">Upvotes: $upvotes</span>
    <span class="downs">Downvotes: $downvotes</span>
    <span class="total">Total votes: $t_votes</span>
    <div id="links">
        <input type="hidden" id="id" name="id" value="$id">
        <a href="process.php?id=$id&f=u" class="upvote"><button>Upvote!</button></a>
        <a href="process.php?id=$id&f=d" class="downvote"><button>Downvote!</button></a>
    </div>
</div>

由PHP返回

更新的更新数。

this不是您所想的。 它的值由它在其中出现的函数的调用方式决定(并且在其他函数中将更改)。

我不知道它将在jQuery成功回调中使用什么,但是它不会成为HTML元素。

如果希望将其作为单击元素,则需要在this元素存储的同时将其存储。

$(".upvote").click(function() {
    var clicked_element = this;

然后,您可以稍后使用该变量:

$(clicked_element).parent().etc

您不能像这样使用this关键字。

var that = null;

$(function()
{
    $(".upvote").click(function()
    {
        var id = $(this).parent().find("input").val();
        that = $(this);
        $.ajax(
        {
            type: "GET",
            url: "process.php",
            data: "id=" + id +"&f=u",

            success: function(results)
            {
                that.parent().parent().find("span.ups").empty().append("Upvotes: " + results);
                console.log(results);
            }
        });
        return false;
    });
});

我没有对此进行测试,但是应该可以。

干杯。

success回调中的$(this)不是您可能认为的元素。 相反,最好缓存父对象并从那里遍历:

var $post = $('.post');

//... $.ajax etc

success: function() {
    $post.find('.ups').etc //...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM