我想对服务器进行 ajax 调用。我需要获取页面 say foo.aspx 的 html: Foo.aspx html:
<form>
<div>foo</div>
</form>
我从远程页面调用此页面,例如:
$.ajax({
url: '/foo.aspx',
data: {},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
}
});
我需要这个页面的 html 但我的要求是这个页面的响应应该是 JSON 格式。即。
{"myresponse": {
"id": "123",
"html":<HTML of foo.aspx>,
}}
我需要 html 作为 json 属性,因为我还需要从后面的 foo.aspx 代码设置其他属性? 如何从 json 格式而不是纯 html 格式的 aspx 页面获取响应? 从服务器以 json 格式获取远程页面的 HTML + 其他属性的另一种方法是什么?我应该选择 HTTPHandlers 吗?如果是,我如何在那个 HTTPHandler 中获取 foo.aspx 的 html?
最佳答案
您可能想尝试覆盖页面的呈现方法:
protected override void Render(HtmlTextWriter writer)
{
var sw = new System.IO.StringWriter();
var tw = new HtmlTextWriter(sw);
base.Render(tw);
Response.Write(String.Format("{{\"myresponse\": {{ \"id": \"123",\"html\":\"{0}\"}}}}"
, Server.HtmlEncode(sw.ToString()).Replace("\n"," "));
Response.Flush();
Response.End();
}
对于任何语法错误以及回车的基本处理,我们深表歉意。 我想在 page_load 期间缓冲输出会更好(Response.BufferOutput = true)
关于c# - 以 json 格式而不是纯 html 从 aspx 页面获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9993372/