which web service works well with Ajax(JavaScript)?
要回答这个问题, 要搞清楚三个问题, Ajax的基本工作原理, SOAP协议, 和REST协议.首先我们可以肯定的说Ajax原理和REST协议的出发点不谋而合.为什么? Ajax的原理是利用javascript中的XMLHttpRequest object, 向服务器端发送http请求, 这个javascript的object在运行时是依赖于浏览器的js引擎的, 也可以认为这些http请求是由浏览器发出的,我们知道浏览器发送的http请求只有header信息, 没有body, 那么请求发送的参数在哪里能体现出来? 学过servlet的都知道, servlet利用了HTTP协议的GET, POST请求, 参数可以在这两个请求的URL中传递给服务器端程序.
下面是一个SOAP请求, 我们SOAP协议是在HTTP的body中加入了SOAP的message, SOAP请求的参数是写在HTTP body中的SOAP message里.注意看下面的例子中服务器要求发送一个公司的名字来查询这个公司的股票价格. SOAP的 <env:Body>中传入了IBM(注意, SOAP消息格式本身也分header和body, 但整个SOAP消息都是在HTTP的body中), 但这个参数在HTTP header上是看不出来的.必须要求客户端有专门处理HTTP body中的SOAP引擎, 来给IBM这个参数包装一层SOAP的外衣. 而单凭XMLHttpRequest是做不到的. 即使想做也需要很多额外的js代码, 这样做会使客户端的js开发变得复杂.
再看一下REST的请求的例子, 你会发先IBM这个参数可以在GET请求上的URL传递, 这是个巧妙的设计, XMLHttpRequest根本不需要做任何对http body的处理. 发送的HTTP请求有header就足够了.而返回的结果也只是普通的xml, 这个xml并不需要包裹在SOAP的body中(注意观察REST的response中的xml和SOAP的response中的xml有什么不同) , 这样, XMLHttpRequest收到结果后就可以从xml中解析出股票价格, 而不需要先解析SOAP, 在解析SOAP body中的xml, 从xml中在解析出股票价格. 中间可以省去对SOAP的处理.
PS: Despite the name XMLHttpRequest object, the use of XML is not required (JSON is often used instead of xml in AJAX), and the requests do not need to be asynchronous.
由此可见, REST更适合和AJAX协同工作.
其实REST设计的初衷就是对HTTP协议的充分利用, HTTP不仅有GET和POST方法, 还有PUT和DELETE方法, 这四个方法涵盖了增删查改功能.
The origin of the term "REST" comes from the famous thesis from Roy Fielding describing the concept of Representative State Transfer (REST). REST is an architectural style that can be summed up as four verbs (GET, POST, PUT, and DELETE from HTTP 1.1) and the nouns, which are the resources available on the network (referenced in the URI). The verbs have the following operational equivalents:
HTTP CRUD Equivalent
==============================
GET read
POST create,update,delete
PUT create,update
DELETE delete
A service to get the details of a user called 'dsmith', for example, would be handled using an HTTP GET to http://example.org/users/dsmith. Deleting the user would use an HTTP DELETE, and creating a new one would mostly likely be done with a POST. The need to reference other resources would be handled using hyperlinks (the XML equivalent of HTTP's href, which is XLinks' xlink:href) and separate HTTP request-responses.
而在servlet中我们所做的增删查改都放到了doGet(), doPost()(对应HTTP的GET和POST)方法中, 其实这是对HTTP协议所规定的方法的一种误用, 背离了HTTP设计的初衷, 而REST可以看做对HTTP设计初衷的一种回归. 既然HTTP本身就有了增删查改, 我们要做的就是传递增删查改的资源名字, 我们可以传给IBM, 也可以传给服务器是Google , 只需要把这些参数放到这些方法的URL中的即可. 所以REST架构设计的难点在于对URL的设计, 我们把网站所有的资源都给出一个对应的URL.
A Simple SOAP Example
Putting it all together, below is an example of a simple request-response in SOAP for a stock quote. Here the transport binding is HTTP.
The request:GET /StockPrice/IBM HTTP/1.1Host: example.orgAccept: text/xmlAccept-Charset: utf-8The response:HTTP/1.1 200 OKContent-Type: text/xml; charset=utf-8Content-Length: nnn<?xml version="1.0"?><s:Quote xmlns:s="http://example.org/stock-service"> <s:TickerSymbol>IBM</s:TickerSymbol> <s:StockPrice>45.25</s:StockPrice></s:Quote>