1

我正在使用“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. 我正在加载整个页面,现在使用非空$_GET 值。这清楚地说明了为什么我需要为我想要添加的内容创建一个单独的页面。

4

2 回答 2

2

当您识别出对图像信息的请求时,您会吐出数据,但您没有做任何事情来阻止脚本的其余部分运行。你可以改变

if (isset($_REQUEST['ImageID'])){echo $details[$_REQUEST['ImageID']];}

类似于

if (isset($_REQUEST['ImageID'])){
  echo $details[$_REQUEST['ImageID']];
  exit;
}

不过,我还是建议使用单独的 URL 获取图像信息。毕竟,URL 应该描述在那里找到的资源。

于 2012-11-19T22:59:05.780 回答
1

嗯,那是因为您请求整个页面,Ajax 是成功的,并且按照您的请求将页面返回给您。

Ajax 不适用于同页请求。将处理文件与索引文件分开。

于 2012-11-19T22:57:44.957 回答