JavaScript的REST客户端库
你并不真的需要一个特定的客户端,它对大多数库来说都相当简单。例如,在jQuery的你可以调用通用$.ajax
功能与你想的请求的类型:
$.ajax({
url: 'http://example.com/',
type: 'PUT',
data: 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()
success: function() { alert('PUT completed'); }
});
您可以GET
/POST
/DELETE
或任何替代PUT
。
虽然你可能希望使用一个库,如优秀jQuery,你不必:所有现代浏览器通过XMLHttpRequest API,其中,尽管它的名字,不局限于支持HTTP非常好,其JavaScript实现到XML表示。
下面是在JavaScript中作出同步HTTP PUT请求的例子:
var url = "http://host/path/to/resource";
var representationOfDesiredState = "The cheese is old and moldy, where is the bathroom?";
var client = new XMLHttpRequest();
client.open("PUT", url, false);
client.setRequestHeader("Content-Type", "text/plain");
client.send(representationOfDesiredState);
if (client.status == 200)
alert("The request succeeded!\n\nThe response representation was:\n\n" + client.responseText)
else
alert("The request did not succeed!\n\nThe response status was: " + client.status + " " + client.statusText + ".");
这个例子是同步的,因为这使得它更容易一些,但它很容易使使用此API,以及异步请求。
在网上有数以千计的关于学习XmlHttpRequest的页面和文章 - 他们通常使用术语AJAX--不幸的是我不能推荐一个特定的页面和文章。您可能会发现this reference方便。
jQuery拥有带有REST样式的URI参数模板的JSON-REST插件。根据其使用的描述示例如下:$.Read("/{b}/{a}", { a:'foo', b:'bar', c:3 })
成为“/ bar/foo?c = 3”的GET。
仅供参考我想添加关于ExtJS的信息,如手册中所述:RESTful Web Services。总之,使用方法来指定GET,POST,PUT,DELETE。例如:
Ext.Ajax.request({
url: '/articles/restful-web-services',
method: 'PUT',
params: {
author: 'Patrick Donelan',
subject: 'RESTful Web Services are easy with Ext!'
}
});
如果Accept头是必要的,它可以被设置为所有请求默认:
Ext.Ajax.defaultHeaders = {
'Accept': 'application/json'
};
您还可以使用MVC框架Backbone.js的一样,将提供一个JavaScript模型的数据。对模型的更改将转换为REST调用。
您可以使用此jQuery插件我只是做了:) https://github.com/jpillora/jquery.rest/
支持基本的CRUD操作,嵌套的资源,基本身份验证
var client = new $.RestClient('/api/rest/');
client.add('foo');
client.foo.add('baz');
client.add('bar');
client.foo.create({a:21,b:42});
// POST /api/rest/foo/ (with data a=21 and b=42)
client.foo.read();
// GET /api/rest/foo/
client.foo.read("42");
// GET /api/rest/foo/42/
client.foo.update("42");
// PUT /api/rest/foo/42/
client.foo.delete("42");
// DELETE /api/rest/foo/42/
//RESULTS USE '$.Deferred'
client.foo.read().success(function(foos) {
alert('Hooray ! I have ' + foos.length + 'foos !');
});
如果您发现错误或希望有新的特点,把它们发布该库“问题”页面,请
jQuery还包含一些使用GET和POST的简便快捷方法:http://api.jquery.com/category/ajax/shorthand-methods/ – 2010-07-18 13:49:26
并扩展@Avi Flax的说法,创建它非常简单如果你想要快捷方式,你可以使用你自己的`PUT`和`DELETE`方法。 – zzzzBov 2011-08-08 14:45:16
你如何找回答案的主体?标题? – 2012-03-26 12:02:34