目的是调用一个执行该操作的方法,然后返回一个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);
        }
    });
}


});

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调用中的网址,应该这样做。 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接口继承:

public class GetFileHandler : IHttpHandler, IRequiresSessionState

关于jquery - 如何以标准的Web表单.Net返回JSON对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8072745/

10-12 18:06