JavaScript REST客户端库

是否有一个JavaScript库,允许我执行所有的REST操作(如通过HTTPHTTPS GETPOSTPUTDELETE )?

你并不需要一个特定的客户端,对于大多数的库来说这是相当简单的。 例如,在jQuery中,您可以使用所需的请求types调用通用的$.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或其他来replacePUT

虽然您可能希望使用一个库,比如优秀的jQuery ,但您并不需要:所有现代浏览器都通过XMLHttpRequest API在JavaScript实现中很好地支持HTTP,尽pipe名称不限于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进行asynchronous请求也是相当容易的。

在网上有数以千计的关于学习XmlHttpRequest的页面和文章 – 他们通常使用术语AJAX – 不幸的是我不能推荐一个特定的。 不过你可能会发现这个参考 。

你可以使用这个jQuery插件我刚刚做:) https://github.com/jpillora/jquery.rest/

支持基本的CRUD操作,嵌套资源,基本authentication

  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 !' ); }); 

如果您发现错误或需要新function,请将其发布到存储库的“问题”页面中

jQuery具有REST风格的URI参数模板的JSON-REST插件。 根据其描述使用的例子如下: $.Read("/{b}/{a}", { a:'foo', b:'bar', c:3 })变成GET来“酒吧/富C = 3" 。

作为参考,我想添加关于ExtJS,如手册: REST风格的Web服务中所述 。 总之,使用方法来指定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' }; 

你也可以使用像Backbone.js这样的mvc框架,它将提供一个数据的javascript模型。 对模型的更改将被转换为REST调用。

您可以使用类似于stream行的Restangular的语法来尝试restful.js ,一个与框架无关的RESTful客户端。

Dojo,例如通过JsonRestStore,请参阅http://www.sitepen.com/blog/2008/06/13/restful-json-dojo-data/

您可以使用http://adodson.com/hello.js/

  1. Rest API支持
  2. 内置支持很多网站谷歌,脸谱,Dropbox
  3. 它支持oAuth 1和2支持。