目标是调用一个方法来完成它的事情,然后返回一个 JSON 对象。
我是 JSON 新手。
我有一个default.aspx,其中包含以下代码。现在我想要 Default.aspx.cs 中的普通方法在此处的单击事件上运行。
$(".day").click(function (event) {
var day = $(event.currentTarget).attr('id');
if (day != "") {
$.ajax(
{
type: "POST",
async: true,
url: 'Default.aspx?day=' + day,
data: day,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SUCCESS:" + msg);
// $(".stripp img").attr('src', "data:image/jpg;" + msg);
// $(".stripp").show();
},
error: function (msg) {
console.log("error:" + msg);
}
});
}
});
Default.aspx.cs 看起来与此类似:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["day"] != null)
GetFile(Request.QueryString["day"]);
}
public string GetFile(string day)
{
string json = "";
byte[] bytes = getByteArray();
json = JsonConvert.SerializeObject(bytes);
return json;
}
我哪里出错了? 我应该以某种方式使用它还是仅适用于 Web 服务?
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
最佳答案
我建议使用HttpHandler
。没有页面生命周期(因此速度非常快)和更清晰的代码分离以及可重用性。
向您的项目添加一个“通用处理程序”类型的新项目。这将创建一个新的 .ashx 文件。任何实现IHttpHandler
的类的主要方法是ProcessRequest
。因此,要使用原始问题中的代码:
public void ProcessRequest (HttpContext context) {
if(String.IsNullOrEmpty(context.Request["day"]))
{
context.Response.End();
}
string json = "";
byte[] bytes = getByteArray();
json = JsonConvert.SerializeObject(bytes);
context.Response.ContentType = "text/json";
context.Response.Write(json);
}
更改 AJAX 调用中的 url 即可。 JavaScript 看起来像这样,其中 GetFileHandler.ashx 是您刚刚创建的 IHttpHandler 的名称:
$.ajax(
{
type: "POST",
async: true,
url: 'Handlers/GetFileHandler.ashx',
data: "Day=" + $.toJSON(day),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SUCCESS:" + msg);
},
error: function (msg) {
console.log("error:" + msg);
}
});
另一个需要考虑的小问题是,如果您需要从 Handler 代码本身访问 Session 对象,请确保继承自 IRequiresSessionState
接口(interface):
public class GetFileHandler : IHttpHandler, IRequiresSessionState
关于jquery - 如何在标准 Web 表单 .Net 中返回 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8072745/