在启动 super 简单的 Ajax 调用时,我尝试了多种方法来定位父元素和/或 JS 对象本身。我有 3 个同一类的 div,仅此而已。当我单击一个时,我尝试获取该 DIV 的 .html(responseHere) 以简单地更改其中的内容,但我无法找到一种方法来选择它而不给它 ID 等。
Javascript:
$(document).ready(function(){
$('.box').click(function(){
$.get('ajax.php', function(data){
$(this).html(data);
}, 'json');
});
});
PHP:
<?php
$var = 'This is some new content!';
echo json_encode($var);
?>
HTML:
<div class="box">
Click me to change my content
</div>
编辑:当我用alert()输出$(this)的值时,我只得到[object Object]
最佳答案
您必须保留对单击元素的引用。在 Ajax 回调中,this
引用 window
对象:
$('.box').click(function(){
var self = this;
$.get('ajax.php', function(data){
$(self).html(data);
}, 'json');
});
此外,json_encode
将不起作用,您必须传递数组或对象,但不能传递字符串。创建正确的 JSON:
$var = array('This is some new content!');
echo json_encode($var);
看起来,一个简单的字符串确实是有效的 JSON。
没有理由在这里调用json_encode
。您可以只返回文本:
echo $var;
(这意味着您还必须在 Ajax 调用中将数据类型从 json
更改为 text
)
关于jQuery:将 AJAX 内容加载到 'this' 的父级中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5773756/