【问题标题】:Return data from jQuery callback ASP.NET 2.0从 jQuery 回调 ASP.NET 2.0 返回数据
【发布时间】:2009-12-17 08:48:34
【问题描述】:

我是 jQuery 新手,我正在实现我在 CodeProjects 上找到的示例。

我需要的是从我正在调用的 PageMethod 返回一个带有图像名和新图像索引的字符串。 但是,每次我尝试通过 Response.Write 返回数字以外的其他内容时,回调都会失败,我会进入错误函数。

$(document).ready(function() {

var imageIndex = $("[id$='hdn_imageIndex']");
var app_path = $("[id$='hdn_app_path']");

$("#btn_next").click(function() {

    var json = "{'Index':'" + imageIndex.val() + "'}";
    var ajaxPage = app_path.val() + "/JSONProcessor.aspx?NextImage=1"; //this page is where data is to be retrieved and processed
    var options = {
        type: "POST",
        url: ajaxPage,
        data: json,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        async: false,
        success: function(result) {

            alert("success: " + result.d);
            // I want my return value from my PageMethod HERE.
        },
        error: function(msg) { alert("failed: " + msg.d); }
    };

    var returnText = $.ajax(options).responseText;

});

});

JSONProcessor.aspx 中的 PageMethod 如下所示:

public void NextImage()
{
    System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
    string line = "";
    line = sr.ReadToEnd();
    JObject jo = JObject.Parse(line);

    int newImageIndex = -1;
    int oldImageIndex = int.Parse(Server.UrlDecode((string)jo["Index"]));
    List<string> images = (List<string>)Session["ShowHouseImages"];
    int noOfImages = images.Count;

    if (noOfImages > 0)
    {
        if (oldImageIndex == noOfImages - 1)
        {
            newImageIndex = 0;
        }
        else
        {
            newImageIndex = oldImageIndex + 1;
        }

        string[] result = ChangeImage(newImageIndex, images);

        Response.StatusCode = 200;
        Response.Write("1");
        // What I REALLY WANT TO RETURN IS THIS
        // Response.Write(string.Format("{0};{1};{2}", result[0], result[1], result[2]));
    }

    Response.Write("0");
}

从 WebMethods 返回的 JSON 似乎不是 .NET 2.0 的一部分。这就是我这样做的原因。希望有人能帮帮我。

【问题讨论】:

    标签: c# asp.net jquery ajax


    【解决方案1】:

    据我了解

    Response.Write(string.Format("{0};{1};{2}", result[0], result[1], result[2]));
    

    您没有返回正确的 JSON 对象。它应该看起来像

    Response.Write(string.Format("{{images:[{0},{1},{2}]}}", result[0], result[1], result[2]));
    

    这会返回一个包含三个元素的数组。产生的输出应该是:

    {images:[1,2,3]}
    

    在 JavaScript 中,您可以使用 result.images[0]、result.images1 等访问数据。 我不确定您是否需要指定数组对象名称(图像)。

    我建议您查看JSON website 以更好地理解语法。这样你就可以自己构造复杂的对象了。

    【讨论】:

    • 你拯救了这一天..你真的做到了..谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    相关资源
    最近更新 更多