我正在使用“Head first Ajax”一书中的示例代码。以下是重要的代码:
Index.php - html piece:
<body>
<div id="wrapper">
<div id="thumbnailPane">
<img src="images/itemGuitar.jpg" width="301" height="105" alt="guitar"
title="itemGuitar" id="itemGuitar" onclick="getDetails(this)"/>
<img src="images/itemShades.jpg" alt="sunglasses" width="301" height="88"
title="itemShades" id="itemShades" onclick="getDetails(this)" />
<img src="images/itemCowbell.jpg" alt="cowbell" width="301" height="126"
title="itemCowbell" id="itemCowbell" onclick="getDetails(this)" />
<img src="images/itemHat.jpg" alt="hat" width="300" height="152"
title="itemHat" id="itemHat" onclick="getDetails(this)" />
</div>
<div id="detailsPane">
<img src="images/blank-detail.jpg" width="346" height="153" id="itemDetail" />
<div id="description"></div>
</div>
</div>
</body>
Index.php - 脚本:
function getDetails(img){
var title = img.title;
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "getDetails.php?ImageID=" + escape(title);
request.open("GET", url, true);
request.onreadystatechange = displayDetails;
request.send(null);
}
function displayDetails() {
if (request.readyState == 4) {
if (request.status == 200) {
detailDiv = document.getElementById("description");
detailDiv.innerHTML = request.responseText;
}else{
return;
}
}else{
return;
}
request.send(null);
}
和Index.php:
<?php
$details = array (
'itemGuitar' => "<p>Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it.</p>",
'itemShades' => "<p>Yoko Ono's sunglasses. While perhaps not valued much by Beatles fans, this pair is rumored to have been licked by John Lennon.</p>",
'itemCowbell' => "<p>Remember the famous \"more cowbell\" skit from Saturday Night Live? Well, this is the actual cowbell.</p>",
'itemHat' => "<p>Michael Jackson's hat, as worn in the \"Billie Jean\" video. Not really rock memorabilia, but it smells better than Slash's tophat.</p>"
);
if (isset($_REQUEST['ImageID'])){echo $details[$_REQUEST['ImageID']];}
?>
所有这些代码都是当有人点击缩略图时,页面上会显示相应的文字说明。
这是我的问题。我试图将getDetails.php
代码放在Index.php
内,并修改getDetails
函数,以便var url
为"Index.php?ImageID="...
。当我这样做时,我遇到以下问题:该函数不会显示数组中的文本片段。相反,它会复制整个代码 - 网页等 - 然后在底部再现预期的文本片段。
为什么?
PS:好的,我现在明白我的问题,感谢下面的两个回答。当我调用网址"Index.php?ImageID="...
时,我不只是加载与$_GET
对应的部分。我正在加载整个页面,现在具有非空$_GET
值。这清楚地说明了为什么我需要为我想要添加的内容创建一个单独的页面。
答案 0 :(得分:2)
当您识别出图像信息请求时,您会吐出数据,但是您无法阻止脚本的其余部分运行。你可以改变
if (isset($_REQUEST['ImageID'])){echo $details[$_REQUEST['ImageID']];}
类似
if (isset($_REQUEST['ImageID'])){
echo $details[$_REQUEST['ImageID']];
exit;
}
不过,我建议使用单独的网址作为图片信息。毕竟,URL应描述在那里找到的资源。
答案 1 :(得分:1)
嗯,那是因为您正在请求整个页面,Ajax是成功的,并且正在按照您的要求将页面返回给您。
Ajax不适用于同页请求。保持处理文件与索引文件分开。