麻烦与Ajax响应jQuery的定位麻烦、Ajax、jQuery

2023-09-11 01:16:04 作者:墨迹

我敲我的头在这里试图找出为什么这是行不通的,所以我终于创造了什么我要去的jsfiddle的简化版本,当然,它的工作原理那里。

I'm banging my head here trying to figure out why this isn't working, so I finally created a simplified version of what I'm going on jsFiddle, and of course it works there.

我在做什么 - 悬停一个简单的AJAX调用了一个元素,并把在一个DIV的响应。这里是我的网站上不工作的code ...

What I'm doing - a simple AJAX call on hover over an element, and putting that response in a DIV. Here's the code on my site that is NOT working...

HTML

<div class="profileimage">
   <a href="#">
      <img src="/profilepics/img.jpg" />
      <p>Test Here</p>
   </a>
   <div class="profileInfo"></div>
</div>

的jQuery

$(document).ready(function() {
    $('.profileimage').hover(function() {
        $.ajax({
            url:"getProfile.php",
            success:function(HTML){
                $(this).find('.profileInfo').html(HTML);
            }
        });
    });
});

此外,仅供参考,所有这一切在 getProfile.php 目前是:

<p>RESULTS FROM AJAX</p>

这是什么工作是AJAX请求发生,返回结果还好。如果我更换线的成功函数警报(HTML),可以看我的反应。什么行不通的是,响应从来没有使得它在给 profileInfo 子元素。

What DOES work is that the AJAX request happens, the result is returned okay. If I replace the line in the success function with alert(HTML), I can see the response. What does NOT work is that the response never makes it in to the profileInfo child element.

我以为我的定位是不正确的,所以我创建了一个的jsfiddle(这里)进行测试。原来,定位器工作得很好。

I assumed my locator was incorrect, so I created a jsFiddle (HERE) to test. Turns out, the locator works just fine.

所以,我想我的问题在这里...如果定位器工作好了的jsfiddle,但不是在AJAX请求......是有什么关于它在一个AJAX调用,我需要改变使用方式?我不明白为什么 $(本).find('profileInfo。)HTML(HTML); 不应该只是正常工作,无论我用它在Ajax响应与否。

So I guess my question here is... if the locator works okay in the jsFiddle, but not in the AJAX request... is there something about the way it's used in an AJAX call that I need to change? I don't see why $(this).find('.profileInfo').html(HTML); shouldn't work just fine regardless of whether I'm using it in an AJAX response or not.

任何想法/建议是AP preciated ...

Any thoughts / suggestions are appreciated...

推荐答案

是不正确的情况下。为了解决这个问题,你有多种选择:

The this is not the right context. To fix this you have multiple options:

您可以使用上下文选项:

$.ajax({
    url:"getProfile.php",
    context: this,
    success:function(HTML){
        $(this).find('.profileInfo').html(HTML);
    }
});

或者你可以使用的不同的选择的:

$.ajax({
    url:"getProfile.php",
    success:function(HTML){
        $('.profileimage').find('.profileInfo').html(HTML);
    }
});

或者你可以使用jQuery的绑定,以确保正确的上下文:

or you could use jQuery's bind to ensure the correct context:

$.ajax({
    url:"getProfile.php",
    success: $.proxy(function(HTML){
        $(this).find('.profileInfo').html(HTML);
    }, this)
});

也可以使用关闭这样的(我的最爱):

温故jQuery Ajax,你会有新的发现

or you can use closure like this (my favorite):

var self = this;
$.ajax({
    url:"getProfile.php",
    success: function(HTML){
        $(self).find('.profileInfo').html(HTML);
    }
});