使用Jquery Ajax将html字符串传递给服务器端

Mr.*_*ost 5 c# asp.net ajax jquery

我在这个网站上看到很多答案对我有很大的帮助但是在这个问题上我需要请大家帮助我.

我有一个textarea作为Html编辑器将html内容传递给服务器并将其附加到新创建的Html页面(用于用户POST等),但jquery或ASP.NET不接受jquery通过数据传递的Html内容: {}

- 对于Jquery:

  $("#btnC").click(function (e) {
    e.preventDefault();

    //get the content of the div box 
    var HTML = $("#t").val();

    $.ajax({ url: "EditingTextarea.aspx/GetValue",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String
        success: function (msg) { alert(msg.d); },
        error: function (type) { alert("ERROR!!" + type.responseText); }

    });
Run Code Online (Sandbox Code Playgroud)

和服务器端ASP.NET:

[WebMethod]
public static string GetValue(string num)
{ 
    StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true);
    sw.WriteLine(num);
    sw.Close();       
return num;//return what was sent from the client to the client again 
}//end get value
Run Code Online (Sandbox Code Playgroud)

Jquery部分给我一个错误:传入无效的对象并输入错误 System.Web.Script.Serialization.JavascriptObjectDeserializer.

这就像jquery不接受带有html内容的字符串.我的代码有什么问题?

Sub*_*cob 13

像这样传递它

JSON.stringify({'num':HTML});
Run Code Online (Sandbox Code Playgroud)

您必须正确地将内容字符串化为JSON.HTML可能包含会使JSON表示法无效的synatax.

var dataToSend = JSON.stringify({'num':HTML});
     $.ajax({ url: "EditingTextarea.aspx/GetValue",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: dataToSend , // pass that text to the server as a correct JSON String
            success: function (msg) { alert(msg.d); },
            error: function (type) { alert("ERROR!!" + type.responseText); }

        });
Run Code Online (Sandbox Code Playgroud)


Bib*_*bhu 8

你可以用它

var HTML = escape($("#t").val());
Run Code Online (Sandbox Code Playgroud)

在服务器端,您可以解码它以获取html字符串

HttpUtility.UrlDecode(num, System.Text.Encoding.Default);
Run Code Online (Sandbox Code Playgroud)