Bjö*_*son 16 asp.net ajax jquery json webforms
目标是调用一个方法,然后返回一个JSON对象.
我是JSON的新手.
我有一个default.aspx,其中包含以下代码.现在我希望Default.aspx.cs中的普通方法在这里的click事件上运行.
$(".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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
});
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;
}
Run Code Online (Sandbox Code Playgroud)
我在哪里错了?我应该以某种方式使用它还是仅适用于Web服务?
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Run Code Online (Sandbox Code Playgroud)
Sha*_*hen 33
我建议一个HttpHandler.没有页面生命周期(因此速度极快)和更清晰的代码分离以及可重用性.
将新项添加到"Generic Handler"类型的项目中.这将创建一个新的.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);
}
Run Code Online (Sandbox Code Playgroud)
更改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);
}
});
Run Code Online (Sandbox Code Playgroud)
另一个需要考虑的小问题,如果您需要从Handler代码本身访问Session对象,请确保从IRequiresSessionState接口继承:
public class GetFileHandler : IHttpHandler, IRequiresSessionState
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37428 次 |
| 最近记录: |