我有一个REST服务API,我试图从Javascript访问它,其中包括GET和POST HTTP请求,但我很难从JavaScript中获取包含请求主体的POST命令。
我可以使用Fiddler生成POST请求并获得有效响应,但我无法弄清楚如何在Javascript中编写类似的代码。
Fiddler请求的一个例子可能是:
http://api.mydomain.com/xml/accounts/authenticate?api_key=12345678-1234-1234-1234-123456789012
Request Header:
Host: api.mydomain.com
content-type: text/xml
Content-Length: 123
Request Body:
<Authentication xmlns="http://schemas.mydomain.com/authentication">
<Firstname>Joe</Firstname>
<Lastname>Blow</Lastname>
</Authentication>
当我执行此操作时,Fiddler显示以下原始数据:
POST http://api.mydomain.com/xml/accounts/authenticate?api_key=12345678-1234-1234-1234-123456789012 HTTP/1.1
Host: api.mydomain.com
content-type: text/xml
Content-Length: 143
<Authentication xmlns="http://schemas.mydomain.com/authentication">
<Firstname>Joe</Firstname>
<Lastname>Blow</Lastname>
</Authentication>
这里是我尝试使用Jquery Ajax调用完成同样请求的最佳方案。
function accessArctos() {
$.ajax({
url: 'http://api.mydomain.com/xml/accounts/authenticate?api_key=12345678-1234-1234-1234-123456789012',
type:"POST",
data: '<Authentication xmlns="http://schemas.mydomain.com/authentication"><Firstname>Joe</Firstname><Lastname>Blow</Lastname></Authentication>',
error: function() { alert("No data found."); },
contentType: "text/xml",
success: function (response) {
alert('Success Auth Token:' + response);
}
});
}
当我执行这段代码时,Fiddler显示原始数据如下:
OPTIONS http://api.mydomain.com/xml/accounts/authenticate?api_key=12345678-1234-1234-1234-123456789012 HTTP/1.1
Host: api.mydomain.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:52381
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
我不确定为什么请求正文没有显示出来。我不知道使用Jquery ajax调用是否是处理此类请求的最佳方法。任何帮助将不胜感激!谢谢!