是否有一个JavaScript库,允许我执行所有REST操作,如GET
,POST
,PUT
和DELETE
超过HTTP
或{ {1}})?
答案 0 :(得分:138)
您并不需要特定的客户端,大多数库都相当简单。例如,在jQuery中,您可以使用您要生成的请求类型调用泛型$.ajax
函数:
$.ajax({
url: 'http://example.com/',
type: 'PUT',
data: 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()
success: function() { alert('PUT completed'); }
});
您可以将PUT
替换为GET
/ POST
/ DELETE
或其他任何内容。
答案 1 :(得分:70)
虽然您可能希望使用一个库,例如优秀的jQuery,但您不必:所有现代浏览器都通过XMLHttpRequest API在其JavaScript实现中很好地支持HTTP,尽管它的名称,但不限于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很方便。
答案 2 :(得分:11)
你可以使用我刚刚制作的这个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 !' );
});
如果您发现错误或想要新功能,请将它们发布到存储库的“问题”页面
答案 3 :(得分:8)
jQuery有JSON-REST插件,带有REST风格的URI参数模板。根据其描述使用的例子如下:$.Read("/{b}/{a}", { a:'foo', b:'bar', c:3 })
变为GET到“/ bar / foo?c = 3”。
答案 4 :(得分:6)
作为参考,我想添加有关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'
};
答案 5 :(得分:3)
您还可以使用像Backbone.js这样的mvc框架来提供数据的javascript模型。对模型的更改将转换为REST调用。
答案 6 :(得分:3)
您可以尝试restful.js,这是一个与框架无关的RESTful客户端,使用类似于流行的Restangular的语法。
答案 7 :(得分:1)
Dojo确实,例如通过JsonRestStore,见http://www.sitepen.com/blog/2008/06/13/restful-json-dojo-data/。
答案 8 :(得分:0)