基于JavaScript的REST客户端框架

by baiheinet on 六月 14th, 2009

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

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

function httpGet(url, method, data) {
    var xmlhttp;
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open (method, url + "?" + data, false);
    xmlhttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8&quot ;) ;
    xmlhttp.setRequestHeader ("Content-Length", data.length);
    xmlhttp.send (null);
    if (xmlhttp.Status = 200) return xmlhttp.responseText;
}

function httpPost(url, method, data) {
    var xmlhttp;
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open (method, url, false);
    xmlhttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8&quot ;) ;
    xmlhttp.setRequestHeader ("Content-Length", data.length);
    xmlhttp.send (data);
    if (xmlhttp.Status = 200) return xmlhttp.responseText;
}

function httpPut(url, method, data) {
    var xmlhttp;
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open (method, url, false);
    xmlhttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8&quot ;) ;
    xmlhttp.setRequestHeader ("Content-Length", data.length);
    xmlhttp.send (data);
    if (xmlhttp.Status = 200) return xmlhttp.responseText;
}

function httpDelete(url, method, data) {
    var xmlhttp;
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open (method, url + "?" + data, false);
    xmlhttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8&quot ;) ;
    xmlhttp.setRequestHeader ("Content-Length", data.length);
    xmlhttp.send (null);
    if (xmlhttp.Status = 200) return xmlhttp.responseText;
}

function test() {
    document.write (httpGet("http://localhost/rest/service.asp", "GET", "do=GET&quot ;) );
    document.write (httpGet("http://localhost/rest/service.asp", "POST", "do=POST&quot ;) );
    document.write (httpGet("http://localhost/rest/service.asp", "PUT", "do=PUT&quot ;) );
    document.write (httpGet("http://localhost/rest/service.asp", "DELETE", "do=DELETE&quot ;) );
}

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

评论《基于JavaScript的REST客户端框架》的内容...

相关文章:

“开架式”软件设计是未来之路

使用PHP调用TinyURL API的方法

润乾报表的使用技巧

数据库查询的分页优化技巧

基于REST架构的Web Service设计

关于我们:我的Google Reader - 我的Twitter - 我的饭否 - 我的开心 - 我的Facebook

Published by  Published by xFruits

Original source : http://www.williamlong.info/archives/1826.html...

Rand Posts:


0 Responses to “基于JavaScript的REST客户端框架”

  1. No Comments

Leave a Response