[英]Why does my Ajax function returns my entire code?
我正在使用“Head first Ajax”一书中的示例代码。 以下是重要的代码:
Index.php - html篇:
<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:好的,我现在明白了我的问题,感谢下面的两个回答。 当我调用url "Index.php?ImageID="...
,我不只是加载对应于$_GET
。 我正在加载整个页面,现在使用非null $_GET
值。 这清楚地说明了为什么我需要为我想要添加的内容创建一个单独的页面。
当您识别出图像信息请求时,您会吐出数据,但是您无法阻止脚本的其余部分运行。 你可以改变
if (isset($_REQUEST['ImageID'])){echo $details[$_REQUEST['ImageID']];}
喜欢的东西
if (isset($_REQUEST['ImageID'])){
echo $details[$_REQUEST['ImageID']];
exit;
}
不过,我建议使用单独的URL来显示图像信息。 毕竟,URL应描述在那里找到的资源。
好吧,那是因为你正在请求整个页面,Ajax是成功的,并且正如你所要求的那样将页面返回给你。
Ajax不适用于同页请求。 将处理文件与索引文件分开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.