木子屋 Dnawo's BLOG

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

👤 dnawo 📅 2022-12-11 👁 2017 👍 0 💬 0 🔄 本站原创
图片

客户端使用 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)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 C#声明List和Dictionary直接初始化示例 下一篇 → .NET JSON序列化/反序列化框架Newtonsoft.Js…