4

我需要模拟这个 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"
    })  
});

我仍然有内容类型的文本/html。这样对吗?

4

4 回答 4

3

在您的 jQuery AJAX 调用中尝试 beforeSend:

$( 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"
    })  
});
于 2013-10-25T14:39:10.053 回答
2

它似乎对我有用...您确定您正在查看正确的请求吗?看看下面 JSFiddle 中的 HTTP 请求;它确实包含Content-Type标题:http: //jsfiddle.net/KqGY4/1/

$( document ).ready(function() {
    $.ajax({
      url:"http://fiddle.jshell.net/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"
    })  
});
于 2013-10-25T14:37:10.893 回答
1

您是否尝试过 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"
    })  
});
于 2013-10-25T14:31:31.187 回答
1

如果你仍然想使用 .post() -> 在它之前调用这个函数

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

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

于 2017-10-03T13:14:22.880 回答