论坛首页 Web前端技术论坛

用js直接读取Rss新闻的两种方法

浏览 3301 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-03-13   最后修改:2009-03-13

在这里我主要是用了两种方法:

第一种是直接用js来访问,这种方法的优点是简单,但缺点是不能在firefox上使用

第二种是用prototype进行实现,当然对ie和firefox就都能满足了

但不论你是用哪种方法,都会面临一个问题:

由于客户端浏览器的安全设置问题,从客户端JavaScript脚本中用XMLHttpRequest直接访问第三方的网址是被禁止的。

最简单的方法就是在自己的服务器上添加一个代理,客户端脚本先把请求发送给代理,代理转发请求,把响应发回给客户端脚本。

所以,我们先在自己的服务器上添加一个代理

/**
 * 
 */
package com.sech.web.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * <p>
 * Copyright: Copyright (c) 2009
 * </p>
 * 
 * @author sech
 * 
 * @version 1.0
 */
public class RssRead extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4431127246599359389L;
	private static int READ_BUFFER_SIZE = 1024;

	/**
	 * 
	 */
	public RssRead() {
		// TODO Auto-generated constructor stub
	}

	public void init() throws ServletException {
	}

	// Process the HTTP Get request
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String urlString = request.getParameter("url");		
		writeResponse(response, urlString);
	}

	private void writeResponse(HttpServletResponse response, String urlString)
			throws ServletException {
		try {
			URL url = new URL(urlString);
			URLConnection urlConnection = url.openConnection();
			response.setContentType(urlConnection.getContentType());
			InputStream ins = urlConnection.getInputStream();
			OutputStream outs = response.getOutputStream();
			byte[] buffer = new byte[READ_BUFFER_SIZE];
			int bytesRead = 0;
			while ((bytesRead = ins.read(buffer, 0, READ_BUFFER_SIZE)) != -1) {
				outs.write(buffer, 0, bytesRead);
			}
			outs.flush();
			outs.close();
			ins.close();
		} catch (Exception e) {
			try {
				response.sendError(
						HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e
								.getMessage());
			} catch (IOException ioe) {
				throw new ServletException(ioe);
			}
		}
	}

	// Process the HTTP Post request
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	// Clean up resources
	public void destroy() {
	}
}
然后再在web.xml中配置下:
<servlet>
    <servlet-name>rssread</servlet-name>
    <servlet-class>com.sech.web.servlet.RssRead</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>rssread</servlet-name>
    <url-pattern>/rssread</url-pattern>
  </servlet-mapping>
这样我们就可以直接访问:http://localhost/rssread 了
既然已经建立了服务器代理,那下面我们就进行js的编写.
第一种:
function get_news(servername)
{
	var URL,i;
	var s_wz,e_wz,str,htmlText;
	htmlText = "";
	URL = servername+"rssread?url=http://news.sohu.com/rss/shehui.xml";	
	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.async=false;
	xmlDoc.load(URL);
	nodes = xmlDoc.documentElement.childNodes;
	var ItemN = xmlDoc.getElementsByTagName("item");
	for(i=0;i<7;i++)
	{
		TextTitle = ItemN[i].selectSingleNode("title").text;//获取title内容
		TextLink = ItemN[i].selectSingleNode("link").text;//获取link内容
		//Textdescription = ItemN[0].selectSingleNode("description").text;
		//s_wz = Textdescription.indexOf("src='");
		//e_wz = Textdescription.indexOf("'",s_wz+5);
		//Imgurl = Textdescription.slice(s_wz+5,e_wz);
		htmlText = htmlText + "<LI><a href='"+TextLink+"' target=_blank>"+TextTitle+"</a></LI>"
	}
	return htmlText;

}
 html的调用:
<DIV class=textDiv id="news">
<UL>
<script  language="JavaScript">    
  document.writeln(sendRequest('http://localhost/'))
  </script>   
</UL>
</DIV>
 第二种方法:
var SendRequestAjax = Class.create();

SendRequestAjax.prototype ={ 
 
	initialize: function(servername) { 
		   this.servername = servername;
  },
  
	sendRequest:function(){	
    var url =this.servername+"rssread?url=http://news.sohu.com/rss/shehui.xml";
    var pars = ""; 
    var myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onComplete: this.sendRequestCompleted.bind(this)});
},   

sendRequestCompleted:function(res){ 	 
    var results= res.responseXML; 
    var title = null; 
    var item = null; 
    var link = null; 
    var htmlText="";   
    var items = results.getElementsByTagName("item");     
    for(var i = 0; i <  7; i++) { 
        item = items[i]; 
        link=items[i].getElementsByTagName("link")[0].firstChild.nodeValue; 
        title = items[i].getElementsByTagName("title")[0].firstChild.nodeValue; 
        
        htmlText = htmlText + "<LI><a href='"+link+"' target=_blank>"+title+"</a></LI>"
    }    
    $("news").innerHTML="<UL>"+htmlText+"</UL>";    
}
}; 
function sendRequest(servername) { 
    var oSendRequestAjax = new SendRequestAjax(servername);
    oSendRequestAjax.sendRequest();        
}  
 html代码:
<script type="text/javascript" src="js/prototype.js"></script>
<DIV class=textDiv id="news">
<script  language="JavaScript">    
  (sendRequest('http://localhost/'))
  </script>   
</DIV>
 OK.这样两种方法就都搞定了.
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics