我可以在从数据库中检索数据时显示HTML元素。但是,当通过ajax请求检索数据时,似乎忽略了HTML元素。我想使用ajax请求检索HTML元素。这里的任何帮助将不胜感激。
private class loadvals
{
public string html { get; set; }
}
[System.Web.Services.WebMethod]
public static string GetHtml(int id)
{
connection conn = new connection();
string query = "Select html from table where id = '1'";
using (SqlConnection con = new SqlConnection(conn.GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand(query))
{
List<loadvals> cus = new List<loadvals>();
loadvals row;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
row = new loadvals();
row.post = System.Web.HttpUtility.HtmlEncode(sdr["html"].ToString());
cus.Add(row);
}
}
con.Close();
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(cus);
return serialized;
}
}
}
function javascriptFunction(test) {
$.ajax({
type: "POST",
async: false,
url: "/html.aspx/GetHtml",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var parsed = JSON.parse(r.d);
for (var i = 0; i < parsed.length; i++) {
alert(parsed[i]["html"]);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + " " + textStatus + " " + errorThrown);
}
});
return false;
}
感谢。
答案 0 :(得分:2)
试试这个..
1.Change the datatype to html
2.Remove the Content type from Ajax request.(No data you are sending for request.)
contentType 将数据发送到服务器时,请使用此内容类型。
dataType 您希望从服务器返回的数据类型。如果没有指定,jQuery将尝试根据响应的MIME类型推断它
参考文档。 http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
async: false,
url: "/html.aspx/GetHtml",
dataType: "html",
success: function (r) {
.....
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + " " + textStatus + " " + errorThrown);
}
});
return false;
}
答案 1 :(得分:0)
将ajax属性'dataType:“json”'更改为'dataType:“html”'