简体   繁体   English

如何通过ajax将JSON正确发送到c#[WebMethod]?

[英]how to properly send JSON via ajax to c# [WebMethod]?

I want to send a JSON string via ajax to [WebMethod] . 我想通过ajax将一个JSON字符串发送到[WebMethod] My JSON values contain double quotation marks ( " ). In js, I create an object and convert it to JSON with JSON.stringify(my_object) . Console shows properly formatted JSON (double quotes are masked with \\ ), jsonlint.com confirms it. 我的JSON值包含双引号( " )。在js中,我创建一个对象并使用JSON.stringify(my_object)将其转换为JSON。控制台显示格式正确的JSON(双引号用\\来掩盖), jsonlint.com确认它。

But the problem appears in [WebMethod] . 但问题出现在[WebMethod] After hours of debugging I found out that it ignores masked " and treats them as normal " . 经过几个小时的调试后,我发现它忽略了蒙面"并将它们视为正常" So my properly JSON-formatted string becomes not properly JSON-formatted string. 所以我正确的JSON格式的字符串变得不正确JSON格式的字符串。

Is there a way to fix this? 有没有办法解决这个问题? Changing my input string is not an option (I mustn't get rid of " ). 更改我的输入字符串不是一个选项(我不能摆脱" )。

Here's some code: 这是一些代码:

ajax request: ajax请求:

$.ajax({
    type: 'POST',
    url: 'Test_Page.aspx/Test',
    data: "{json: '" + JSON.stringify(json_string) + "'}",
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (msg) {},
    error: function (msg) {}
});

web method: 网络方法:

[WebMethod]
public static string Test(string json) {
    return Newtonsoft.Json.JsonConvert.SerializeObject(Other_Function(json));
}

Try this: 尝试这个:

$.ajax({
    type: 'POST',
    url: 'Test_Page.aspx/Test',
    data: JSON.stringify({json: json_string}),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (msg) {},
    error: function (msg) {}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM