json中415不支持的媒体类型错误

时间:2014-10-08 08:08:43

标签: jquery ajax json api

您好我正在尝试使用jauery中的json和ajax创建发送数据的代码,但它在restful api中显示错误

function PostAjaxAddClient(UrlAddClient,objData,func, isToken, isContentHeader)
{
    token=456; 
    var url=serviceURL + UrlAddClient;
    alert(objData);
    $.ajax({
        type: "POST",
        data : objData,
        contentType :"application/json",
        url:url,
        beforeSend:function(xhr){
            if(isContentHeader){
                xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            } 
            if(isToken){
                xhr.setRequestHeader("tokenId",token);
            }
        },
        success: function(res){
            alert("success");
            func(res);
        },
        error : function(err) {
            alert("ERROR:STATUS- " + err.status + "; RESPONSETEXT- " + err.responseText + "; STATUSTEXT- " + err.statusText);
            func(err);
        }
    });
}
{
  "first_name": "Jahangir",
  "last_name": "Ansari",
  "business_name": "Ecommerce",
  "website_name": "Craftstrail.com",
  "country_id": 1,
  "contact_number": "8082056464",
  "phoneCode": 3,
  "messangerName": "1",
  "messanger_id": 7876,
  "city": "Thane",
  "state_id": 647,
  "pinCode": "4",
  "status_id": null,
  "network_legal_entity_id": 1,
  "accountType": null,
  "accountManager": 2,
  "businessDevelopement": 2,
  "username": "Bond",
  "password": "gfgdfg"
}

2 个答案:

答案 0 :(得分:0)

您必须将objData转换为json。您可以使用JSON.stringify()

示例:

    function PostAjaxAddClient(UrlAddClient,objData,func, isToken, isContentHeader)
{
    token=456; 
    var url=serviceURL + UrlAddClient;
    alert(objData);
    $.ajax({
        type: "POST",
        data : JSON.stringify(objData),
        contentType :"application/json",
        url:url,
        beforeSend:function(xhr){
            if(isContentHeader){
                xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            } 
            if(isToken){
                xhr.setRequestHeader("tokenId",token);
            }
        },
        success: function(res){
            alert("success");
            func(res);
        },
        error : function(err) {
            alert("ERROR:STATUS- " + err.status + "; RESPONSETEXT- " + err.responseText + "; STATUSTEXT- " + err.statusText);
            func(err);
        }
    });
}

答案 1 :(得分:0)

contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({
    //your properties
})

另请查看here