post请求中的jquery集合头

post请求中的jquery集合头,jquery,Jquery,我需要模拟这个curl命令 curl -i -H "Accept: application/json" -H "Content-type:application/json" -X POST -d '{"username":"pippo","password":"secret123"}' http://url.org/api/login 通过jquery,我以这种方式 $( document ).ready(function() { $.ajax({ url:"http://

我需要模拟这个curl命令

curl -i -H "Accept: application/json" -H "Content-type:application/json" -X POST -d '{"username":"pippo","password":"secret123"}' http://url.org/api/login
通过jquery,我以这种方式

$( document ).ready(function() {
    $.ajax({
      url:"http://urlapi/user/login",
      type:"POST",
      headers: { 
        "Accept" : "application/json; charset=utf-8",
        "Content-Type": "application/json; charset=utf-8"
      },
      data:{ username: "pippo", password: "secret123" },
      dataType:"json"
    })  
});

我仍然有内容类型text/html。是否正确?

您是否尝试过contentType选项

$( document ).ready(function() {
    $.ajax({
      url:"http://urlapi/user/login",
      type:"POST",
      headers: { 
        "Accept" : "application/json; charset=utf-8"
      },
      contentType:"application/json; charset=utf-8",
      data:{ username: "pippo", password: "secret123" },
      dataType:"json"
    })  
});

它似乎对我有用。。。您确定正在查看正确的请求吗?看看下面JSFIDLE中的HTTP请求;它确实包含
内容类型
标题:


请在发送jQuery AJAX调用之前尝试:

$( document ).ready(function() {
    $.ajax({
      url:"http://urlapi/user/login",
      type:"POST",
      beforeSend: function(xhr){
                xhr.setRequestHeader("Content-Type","application/json");
                xhr.setRequestHeader("Accept","application/json");
      },
      data:{ username: "pippo", password: "secret123" },
      dataType:"json"
    })  
});

如果仍要使用.post()->请在调用此函数之前调用它

$.ajaxSetup({
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
});

之后的所有jquery请求都将包含这些标题。

这似乎是正确的。您有什么问题吗?
$.ajaxSetup({
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
});