JQuery Ajax POST -请求体不显示在原始HTTP请求

JQuery Ajax POST - Request Body not showing up in Raw HTTP Request

本文关键字:请求 显示 原始 HTTP Ajax POST JQuery      更新时间:2023-09-26

我有一个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调用是否是处理这类请求的最佳方法。任何帮助将不胜感激!

谢谢!

查看responseText

success: function (response, status, xhr) {
    console.log(xhr.responseText);
    alert('Success Auth Token:' + response);
}

您可能会在那里看到正确的文本,但是responseXml将为空,因为文档无效。

为什么?因为你漏掉了

这行
<?xml version="1.0" encoding="ISO-8859-1"?>

这将使它成为一个有效的XML文档