从jQuery回调ASP.NET 2.0返回数据

时间:2009-12-17 08:48:34

标签: c# asp.net jquery ajax

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

我需要的是从我正在调用的PageMethod返回一个带有imagename和新图像索引的字符串。 但是,每当我尝试通过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的一部分。这就是我这样做的原因。希望有人可以帮助我。

1 个答案:

答案 0 :(得分: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.images 1等访问数据。 我不确定你是否需要指定数组对象名称(图像)。

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

相关问题