Ami*_*rad 116 javascript rest jquery
是否有一个JavaScript库,它允许我执行像(所有的REST操作GET
,POST
,PUT
和DELETE
超过HTTP
或HTTPS
)?
ale*_*emb 139
您并不真正需要特定的客户端,大多数库都相当简单.例如,在jQuery中,您可以$.ajax
使用您要进行的请求类型调用泛型函数:
$.ajax({
url: 'http://example.com/',
type: 'PUT',
data: 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()
success: function() { alert('PUT completed'); }
});
Run Code Online (Sandbox Code Playgroud)
您可以替换PUT
用GET
/ POST
/ DELETE
或什么的.
Avi*_*lax 70
虽然您可能希望使用库,例如优秀的jQuery,但您不必:所有现代浏览器都通过XMLHttpRequest API在其JavaScript实现中非常好地支持HTTP ,尽管XMLHttpRequest API的名称不仅限于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 + ".");
Run Code Online (Sandbox Code Playgroud)
这个例子是同步的,因为它使它更容易一些,但是使用这个API也很容易发出异步请求.
网上有成千上万的关于学习XmlHttpRequest的页面和文章 - 他们通常使用术语AJAX - 遗憾的是我不能推荐一个特定的.你可能会发现这个参考方便.
jpi*_*ora 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 !' );
});
Run Code Online (Sandbox Code Playgroud)
如果您发现错误或想要新功能,请将它们发布到存储库的"问题"页面中
作为参考,我想添加有关ExtJS的内容,如手册:RESTful 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!'
}
});
Run Code Online (Sandbox Code Playgroud)
如果需要Accept标头,则可以将其设置为所有请求的默认值:
Ext.Ajax.defaultHeaders = {
'Accept': 'application/json'
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
216672 次 |
最近记录: |