其他事件代码讲解
新闻详细页返回主页的事件代码
在第一部分中,曾经提到在新闻详细内容页的头部和底部都有按钮返回到主页,其代码如下,非常简单,只是调用showCategories代码,具体见下载附件。
var buttonHdrShowCategoriesVar = $('#buttonHdrShowCategories');
var buttonFtrShowCategoriesVar = $('#buttonFtrShowCategories');
buttonHdrShowCategoriesVar.click(function() {
showCategories();
return false;
});
buttonFtrShowCategoriesVar.click(function() {
showCategories();
return false;
});
var buttonFtrShowCategoriesVar = $('#buttonFtrShowCategories');
buttonHdrShowCategoriesVar.click(function() {
showCategories();
return false;
});
buttonFtrShowCategoriesVar.click(function() {
showCategories();
return false;
});
关于AJAX请求
最后我们来讨论ajax请求部分,在这里,我们是通过使用bridge.php作为中转,对Yahoo的新闻发起ajax请求,重新复习下getNews的代码:
var NEWS_URI = 'bridge.php?fwd=http://rss.news.yahoo.com/rss/';
function getNews(varCat,handler){
var varURI = NEWS_URI + varCat;
$.ajax({type: GET, dataType: XML, url: varURI, success: handler});
return false;
}
function getNews(varCat,handler){
var varURI = NEWS_URI + varCat;
$.ajax({type: GET, dataType: XML, url: varURI, success: handler});
return false;
}
在上面的代码中,index.html和bridge.php都运行在同一服务器环境中,实际向yahoo发出的请求会是这个样子:
bridge.php?fwd=http://rss.news.yahoo.com/rss/business,而bridge.php会通过php的cUrl方法向Yahoo发出请求,将获得的xml信息写在文件tmpFile.txt中,具体代码如下,关于php的cUrl方法请参考PHP手册,这里不再详细介绍。
<?php
header('Content-Type: application/xml');
$tmpFile = 'tmpFile.txt';
$val = $_GET["fwd"];
$curlHandle = curl_init($val);
$filePointer = fopen($tmpFile, "w");
curl_setopt($curlHandle, CURLOPT_FILE, $filePointer);
curl_exec($curlHandle);
curl_close($curlHandle);
fclose($filePointer);
$linesArr = file($tmpFile);
foreach($linesArr as $eachLine){
echo($eachLine);
}
?>
header('Content-Type: application/xml');
$tmpFile = 'tmpFile.txt';
$val = $_GET["fwd"];
$curlHandle = curl_init($val);
$filePointer = fopen($tmpFile, "w");
curl_setopt($curlHandle, CURLOPT_FILE, $filePointer);
curl_exec($curlHandle);
curl_close($curlHandle);
fclose($filePointer);
$linesArr = file($tmpFile);
foreach($linesArr as $eachLine){
echo($eachLine);
}
?>