JQuery ajax 把后台返回的List数据 遍历出来 赋值给div

时间:2024-03-01 19:34:34

1、效果

2、前端代码


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>testPic</title>
    <script src="IndusJS/jquery.min.js"></script>    
    <script type="text/javascript">
        var tt1 = 0;
        var myArr = new Array();
        $(function () {
            $.ajax({
                type: "post",
                url: \'Home/getTestDICData\',
                data: { pid: 1 },
                dataType: "json",
                success: function (data) {
                    var ImageContent = "";
                    $.each(data, function (index, val) {
                        if (index == "picBase64") {
                            if (val.length > 0) {
                                for (var i = 0; i < val.length; i++) {
                                   ImageContent += \'<span>key:"\' + val[i].ID + \'";</span><span>value:"\' + val[i].valName + \'"</span>\';
                                }
                                $(\'#imgCon\').html(ImageContent);
                            }
                        }
                        else {                   
                            $(\'#\' + index + \'\').val(value);
                        }
                    });
                },
                error: function (data) {
                    console.log(data);
                }
            });      
        });</script>
</head>
<body>

    <div id="imgCon">    
    </div>

</body>
</html>

2、后台代码

        public JsonResult getTestDICData()
        {
            picModel model = new picModel();
            subPicMolde k1 = new subPicMolde() { ID=1, valName="值1" };
            subPicMolde k2= new subPicMolde()  { ID = 2, valName = "值2" };
            subPicMolde k3 = new subPicMolde() { ID = 3, valName = "值3" };
            subPicMolde k4 = new subPicMolde() { ID = 4, valName = "值4" };
            List<subPicMolde> myList = new List<subPicMolde>();
            myList.Add(k1);
            myList.Add(k2);
            myList.Add(k3);
            myList.Add(k4);
            model.picBase64 = myList;
           return Json(model,JsonRequestBehavior.DenyGet);
        }

  public class picModel
    {
        public List<subPicMolde> picBase64;
    }

   public class subPicMolde
    {
        public int ID { get; set; }
        public string valName { get; set; }
    }