Chinaunix首页 | 论坛 | 博客
  • 博客访问: 40781
  • 博文数量: 11
  • 博客积分: 69
  • 博客等级: 民兵
  • 技术积分: 96
  • 用 户 组: 普通用户
  • 注册时间: 2011-12-13 01:21
文章分类
文章存档

2012年(6)

2011年(5)

我的朋友

分类:

2012-01-12 22:31:11

现在REST是一个比较热门的概念,REST已经成为一个在Web上越来越常用的应用,基于REST的Web服务越来越多,包括Twitter在内的微博客都是用REST做为对外的API,先前我曾经介绍过“基于REST架构的Web Service设计”,并给出了一些服务器端和客户端代码,随着JavaScript的广泛应用,我这里就给出一个轻量级的基于JavaScript的REST客户端框架。

这个JavaScript客户端主要使用了XMLHttpRequest对象来实现通过HTTP对服务器操作GET、PUT、POST和DELETE以检索和修改资源。值得注意的是,由于安全方面的考虑,Javascript被限制了跨域访问的能力,因此在调用XMLHttpRequest的时候,应该注意跨域访问的问题,比如使用同一个域的动态文件做代理,或者其他方法避开跨域访问的问题。我这里给出的代码主要是根据我先前的那段代码修改过来的,其客户端JavaScript代码如下所示:

  1. function httpGet(url, method, data) {  
  2.     var xmlhttp;  
  3.     xmlhttp = new XMLHttpRequest();  
  4.     xmlhttp.open (method, url + "?" + data, false);  
  5.     xmlhttp.setRequestHeader ("Content-Type""application/x-www-form-urlencoded; charset=UTF-8");  
  6.     xmlhttp.setRequestHeader ("Content-Length", data.length);  
  7.     xmlhttp.send (null);  
  8.     if (xmlhttp.Status = 200) return xmlhttp.responseText;  
  9. }  
  10.  
  11. function httpPost(url, method, data) {  
  12.     var xmlhttp;  
  13.     xmlhttp = new XMLHttpRequest();  
  14.     xmlhttp.open (method, url, false);  
  15.     xmlhttp.setRequestHeader ("Content-Type""application/x-www-form-urlencoded; charset=UTF-8");  
  16.     xmlhttp.setRequestHeader ("Content-Length", data.length);  
  17.     xmlhttp.send (data);  
  18.     if (xmlhttp.Status = 200) return xmlhttp.responseText;  
  19. }  
  20.  
  21. function httpPut(url, method, data) {  
  22.     var xmlhttp;  
  23.     xmlhttp = new XMLHttpRequest();  
  24.     xmlhttp.open (method, url, false);  
  25.     xmlhttp.setRequestHeader ("Content-Type""application/x-www-form-urlencoded; charset=UTF-8");  
  26.     xmlhttp.setRequestHeader ("Content-Length", data.length);  
  27.     xmlhttp.send (data);  
  28.     if (xmlhttp.Status = 200) return xmlhttp.responseText;  
  29. }  
  30.  
  31. function httpDelete(url, method, data) {  
  32.     var xmlhttp;  
  33.     xmlhttp = new XMLHttpRequest();  
  34.     xmlhttp.open (method, url + "?" + data, false);  
  35.     xmlhttp.setRequestHeader ("Content-Type""application/x-www-form-urlencoded; charset=UTF-8");  
  36.     xmlhttp.setRequestHeader ("Content-Length", data.length);  
  37.     xmlhttp.send (null);  
  38.     if (xmlhttp.Status = 200) return xmlhttp.responseText;  
  39. }  
  40.  
  41. function test() {  
  42.     document.write (httpGet("""GET""do=GET"));  
  43.     document.write (httpGet("""POST""do=POST"));  
  44.     document.write (httpGet("""PUT""do=PUT"));  
  45.     document.write (httpGet("""DELETE""do=DELETE"));  
  46. }  

我这里使用这个代码编写了一个简单的应用例子,就是管理Twitter好友的应用,大家点这里可以下载使用,因为跨域访问的问题,这段JavaScript只支持IE在本地使用。

阅读(1609) | 评论(0) | 转发(0) |
0

上一篇:Tomcat处理HTTP请求:Connector源码

下一篇:没有了

给主人留下些什么吧!~~