jQuery不发送内容类型为application / json的post请求

时间:2013-07-01 10:16:52

标签: javascript jquery ajax http-headers cross-domain

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

    $.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,status = 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设置我想要的内容类型标题?

2 个答案:

答案 0 :(得分:1)

访问控制原产地。

浏览器不允许在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)。

答案 1 :(得分:-1)

试试这个


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)
        }
    })