jQuery.ajax向服务器端post提交json数据错误及解决方法



客户端使用 jQuery.ajax向服务器端post提交json数据,代码如下:

apiPost = function(url, data){
    $.ajax({        
        url: url,        
        data: data,
        type: "post",
        async: true,
        dataType: "json",
        contentType: "application/json",
        success: function(response){console.log(response)}
    });
}

data = {"domain":"mzwu.com","date":"2005-03-28"};
apiPost("demo.ashx", data);

测试发现服务器端获取到的数据不是json格式,而是key/value格式:domain=mzwu.com&date=2005-03-28,对代码稍做修改(data加单引号):

data = '{"domain":"mzwu.com","date":"2005-03-28"}';
apiPost("demo.ashx", data);

测试正常了,但这样不便于修改json数据,借助JSON.stringify方法,完美解决:

apiPost = function(url, data){
    $.ajax({        
        url: url,        
        data: JSON.stringify(data),
        type: "post",
        dataType: "json",
        async: true,
        contentType: "application/json",
        success: function(response){console.log(response)}
    });
}

data = {"domain":"mzwu.com","date":"2005-03-28"};
data.date = "2022-12-11";
apiPost("demo.ashx", data);


评论: 0 | 引用: 0 | 查看次数: 665
发表评论
登录后再发表评论!