标准的XMLHttpRequest有效,但在发布到REST服务时jQuery$.ajax无效

standard XMLHttpRequest works, but not jQuery $.ajax when POSTing to REST service

本文关键字:服务 REST jQuery 无效 ajax 有效 XMLHttpRequest 标准      更新时间:2023-09-26

我想对REST服务进行POST。当使用标准的XMLHttpRequest时,它的工作方式是,但当使用jQuery$.ajax时,HTTPRequest标头会变得混乱,POST变成OPTIONS。

我是jQuery和HTTP的新手,所以我可能错过了一些显而易见的东西:)

这项工作:

function sendPostXMLHTTP() {
    var jData = { "Name": "Olle" };
    var client = new XMLHttpRequest();
    client.open("POST", "http://localhost:8383/DEMOService/TestPost");
    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    client.send(JSON.stringify(jData));
}

这不起作用:

function sendPostAjax() {
    var jData = { "Name": "Olle" };
    $.ajax({
        type: 'POST',
        url: 'http://localhost:8383/DEMOService/TestPost',
        contentType: "text/plain;charset=UTF-8",
        data: JSON.stringify(jData)
    });
}

从sendPostXMLHTTPRequest()生成的HTTPRequest(正确):

POST http://localhost:8383/DEMOService/TestPost HTTP/1.1
Host: localhost:8383
Connection: keep-alive
Content-Length: 15
Origin: http://localhost:9990
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
Content-Type: text/plain;charset=UTF-8
Accept: */*
Referer: http://localhost:9990/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
{"Name":"Olle"}

从sendPostAjax()生成的HTTPRequest不正确

OPTIONS http://localhost:8383/DEMOService/TestPost HTTP/1.1
Host: localhost:8383
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:9990
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
Access-Control-Request-Headers: Origin, X-Requested-With, Content-Type, Accept
Accept: */*
Referer: http://localhost:9990/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

为什么";jQuery$.ajax&quot-如何将POST转换为OPTIONS,为什么请求主体会消失?

jQuery假设您正在执行一个跨来源资源共享请求。根据W3C标准,任何CORS请求之前都必须有一个空的OPTIONS请求,请求服务器允许带有有效负载的后续请求。

您是否正在向脚本所在的其他服务器发出请求?

如果是,那么jQuery的请求是正确的,而XMLHttpRequest的请求则不是——您应该自己实现OPTIONS preflight请求。

如果没有,那么您应该考虑更改配置中的某些内容——例如,将脚本移动到REST服务所在的同一网站。

或者,正如评论中所建议的,这可能是您正在使用的jQuery或浏览器中的一个错误。

试试看:

var jData = {name:'Olle'};
  $.ajax({
  url : 'http://localhost:8383/DEMOService/TestPost',
  type : 'POST',
  data : jData
});

数据将始终使用UTF-8字符集传输到服务器;您必须在服务器端对其进行适当的解码。另请参阅API