基于JavaScript的REST客户端框架(转)
转自月光博客 http://www.williamlong.info/archives/1826.html
现在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");
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");
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");
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");
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"));
document.write (httpGet(
"http://localhost/rest/service.asp", "POST", "do=POST"));
document.write (httpGet(
"http://localhost/rest/service.asp", "PUT", "do=PUT"));
document.write (httpGet(
"http://localhost/rest/service.asp", "DELETE", "do=DELETE"));
}
我这里使用这个代码编写了一个简单的应用例子,就是管理Twitter好友的应用,大家点这里可以下载使用,因为跨域访问的问题,这段JavaScript只支持IE在本地使用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!