jQuery 不会发送内容类型为 application/json 的帖子请求



我正在使用jQuery 1.10.1。我想发送POST请求,内容类型设置为application/json。我正在做以下事情:

    $.ajax({
        type: "post",
        url: urlBase + "user/search",
        contentType: "application/json; charset=utf-8", 
        data: JSON.stringify(filter), 
        success: renderResponse,
        error: function(error) {
            console.log(error)
        }
    })

但是POST没有发送,我在错误回调时得到了以下响应:

对象{readyState=0,state=0,statusText="error"}

生成OPTIONS重新请求,但没有POST。以下是OPTIONS请求和响应:

Antwort-Header
Access-Control-Allow-Head...    X-Requested-With
Access-Control-Allow-Meth...    GET, POST, OPTIONS
Access-Control-Allow-Orig...    *
Access-Control-Max-Age  86400
Allow   GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
Content-Length  0
Server  Jetty(6.1.1)
Anfrage-Header
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Access-Control-Request-He...    content-type
Access-Control-Request-Me...    POST
Cache-Control   no-cache
Connection  keep-alive
Host    localhost:8080
Origin  http://localhost
Pragma  no-cache
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0

这里有什么问题?如何让jQuery设置我想要的内容类型标题?

访问控制源代码。

浏览器不允许在JavaScript中设置Content-Type标头。解决方案是修改响应头(Java中的示例):

    HttpServletResponse hresp = (HttpServletResponse) resp;
    hresp.addHeader("Access-Control-Allow-Origin", "*");
    hresp.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");

它不是特定于jquery的,但它也适用于每个AJAX请求(Dojo或纯javascript)。

试用


var postData = JSON.stringify({"key": value});//this will be your json content
$.ajax({
        type: "post",
        url: urlBase + "user/search",
        contentType: "application/json; charset=utf-8", 
        data: postData,
dataType: "json," 
        success: renderResponse,
        error: function(error) {
            console.log(error)
        }
    })

相关内容

  • 没有找到相关文章

最新更新