传递HTML字符串使用jQuery的Ajax服务器端字符串、服务器端、HTML、Ajax

2023-09-10 19:28:21 作者:︶ㄣ满天花瓣渲染离别ㄣ︶

我已经看到了很多在这个网站答案,帮了我很多,但在这其中我要问你们帮我出。

i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.

我有一个textarea为HTML编辑器的HTML内容传递到服务器并将其附加到新创建的HTML页面(网友发帖,等),但jQuery的或ASP.NET不接受的jQuery通过HTML内容通过数据:{}

i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}

- jQuery的:

--For 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); }

    });

和服务器端ASP.NET:

and Server-Side 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

jQuery的一部分,给我一个错误: 传递和错误无效的对象 System.Web.Script.Serialization.JavascriptObjectDeserializer。

Jquery part gives me an error: Invalid object passed in and error in System.Web.Script.Serialization.JavascriptObjectDeserializer.

这就像jQuery的犯规接受字符串HTML content.what不对我的code?

It's like jquery doesnt accept string with html content.what is wrong with my code ?

推荐答案

它传递这样

JSON.stringify({'num':HTML});

您必须字符串化的内容,以JSON正常。 HTML可能包含synataxes这将使JSON表示法无效。

You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.

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); }

        });