c#
  • asp.net
  • jquery
  • ajax
  • 2009-12-17 104 views 0 likes 
    0

    我是jQuery的新手,我正在实现一个我在CodeProjects上找到的示例。从jQuery回调返回数据ASP.NET 2.0

    我需要的是从我打电话给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; 
    
    }); 
    

    });

    的PageMethod的在JSONProcessor.aspx看起来是这样的:从的WebMethods

    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"); 
    } 
    

    JSON回报似乎并没有成为.NET 2.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以更好地理解语法。这样你就可以自己构建复杂的对象。

    +0

    你保存了一天..你真的..谢谢! – 2009-12-17 09:20:58

    +0

    欢迎你( - 。 – Audrius 2009-12-17 10:05:09

    相关问题