我有一个包含 div1 和 div2 的网站。 div1 包含一个按钮,该按钮触发一个 ajax 函数,该函数连接到一个 PHP 文件,该文件从数据库获取一些内容。然后数据库会回显一些输出。问题是这个输出显示在与按钮所在的同一个 div 中。我需要它显示在 div2 而不是 div1 中。
我听说这可以使用 JQuery 来完成,因为它可以将一些回显代码从一个 div 移动到另一个 div,但我找不到与我的问题相关的任何内容。也许你知道。
下面是一些可能有助于理解问题的代码:
<div id="house_wall1"> //This is the div2
<?php if (login_check($mysqli) == true): ?>
<?php
require('database/refresh_house.php');
//This is the place I want the element echo'ed out.
?>
</div>
这里是数据库调用,使用ajax调用。
if ($stmt = $mysqli->prepare('SELECT x, y, z, src, rotation, link, div_id FROM house_room1 INNER JOIN objects ON house_room1.object_id=objects.object_id WHERE house_room1.ref_id = ?')) {
$stmt->bind_param('i', $item_number);
$stmt->execute();
$stmt->bind_result($x, $y, $z, $src, $rotation, $link, $div_id);
$data = '';
while($stmt->fetch()) {
if ($link != "") {
$data.='<a href="' . $link . '"> ';
}
if ($div_id != "") {
$data.= '<a href="#" onClick="' . $div_id . '"> ';
}
$data.= '<img src="' . $src . $rotation .'.png" class="item' . $item_number . '" style="position:absolute; left:' . $x . 'px; top:' . $y . 'px; z-index:'. $z . ';">'; if ($x != 0) { echo'</a>'; }
}
} else {
echo 'Something went terrible wrong' . $mysqli->error;
}
$stmt->close();
正如你所看到的,它在 while 循环中回显了一些内容,这个 while 循环回显了错误的 div,我需要将其显示在 div2 中。我不认为使用 include
是可能的,因为代码必须是 Ajax 函数的一部分。由于 Ajax 是异步的,因此它必须存在。
嗯,任何想法、意见或建议都值得赞赏。谢谢。
Ajax 代码:
function rotateObject(e)
{
//e is handler which contains info about the item clicked. From that we can obtain the image id.
//since the id are of the form img_123(some number), we need to extract only the number.
var img_id = e.id.split("_")[1];
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("item-2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","database/update_settings_rotate.php",true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("item_id="+encodeURIComponent(img_id));
}
最佳答案
这是关键行:
document.getElementById("item-2").innerHTML=xmlhttp.responseText;
如果您希望在该 div 中显示对 AJAX 请求的响应,则需要指定该 div2 的元素 ID。
关于javascript - 使用 JQuery 将 PHP echo 移动到另一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22376866/