繁体   English   中英

ASP.NET Web服务使用jQuery返回List <>

[英]ASP.NET WebService returning List<> using jQuery

这是我的WebService方法:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

public string getlastimages()
{
    DBservices DBS = new DBservices();
    List<string> ImageUrls = new List<string>();
    try
    {
       DBS.getLastImages();
       ImageUrls = DBS.ImgUrlList;
    }
    catch(Exception ex)
    {
        throw ex;
    }

    JavaScriptSerializer js = new JavaScriptSerializer();
    string jsonImage = js.Serialize(ImageUrls);
    return jsonImage;
}

这是我运行此方法后收到的数据:

<string xmlns="http://tempuri.org/">
["~\\images\\benny\\1149468-18.jpg","~\\images\\lior\\photo4.jpg","~\\images\\oren\\photo3.jpg","~\\images\\oren\\photo2.jpg","~\\images\\oren\\photo1.jpg"]
</string>

我是$ .ajax方法的新手,我需要编写$ .ajax方法来帮助从该列表中检索此数据。 任何帮助都会很棒。

您无需将List<string>转换为json格式的字符串。 由于已经使用[ScriptMethod(ResponseFormat = ResponseFormat.Json)]装饰,因此将使用JavaScriptSerializer在内部对其进行处理。 检查MSDN

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script
[ScriptService]
public class Service: System.Web.Services.WebService 
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]    
    public List<string> getlastimages()
    {
      DBservices DBS = new DBservices();
      List<string> ImageUrls = new List<string>();
      try
      {
       DBS.getLastImages();
       ImageUrls = DBS.ImgUrlList;
      }
      catch(Exception ex)
      {
        throw ex;
      }
      return ImageUrls;
    }
}

jQuery的

$.ajax({

url:"service.asmx/getlastimages",
type:"POST",
dataType:'json',
contentType: "application/json; charset=utf-8",
success:function(data){
   var result;
   if (data.hasOwnProperty('d')) {
    result=data.d;// ASP.Net framework will add d
   }
   else
   {
    result=data;
   }
}
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM