未捕获的TypeError:无法使用'in'运算符以JSON格式搜索“length”

时间:2018-02-22 08:41:08

标签: c# json ajax razor asp.net-mvc-5

我正在尝试使用AJAX从我的数据库中获取数据并将该数据放入我的jQuery FullCalendar中。虽然在尝试获取数据时出现错误。

  

未捕获TypeError:无法使用'in'运算符在[(JSON对象)]中搜索“length”

当我console.log(doc)时,我得到了一个正确的JSON对象,我使用JSON Formatter & Validator验证了

昨天我就一个不同的错误提出了一个问题,但是相同的脚本HERE是一些额外的信息,可以看到我尝试了什么,以及我是如何达到这一点的。

这是console.log(obj)

的输出
[  
{  
  "id":1,
  "title":"K. Keesen",
  "desc":"zelf ziek gemeld",
  "start":"2-2-2018 13:00:00",
  "end":"5-2-2018 13:00:00",
  "user":15,
  "melding":1
  },
  {  
  "id":3,
  "title":"K. Keesen",
  "desc":null,
  "start":"2-2-2018 13:00:00",
  "end":"5-2-2019 13:00:00",
  "user":15,
  "melding":1
  },
  {  
  "id":5,
  "title":"K. Keesen",
  "desc":null,
  "start":"14-2-2018 08:30:00",
  "end":"",
  "user":15,
  "melding":1
  },
  {  
  "id":6,
  "title":"K. Keesen",
  "desc":"srgsrgrgdrgdrgd",
  "start":"7-2-2018 08:30:00",
  "end":"",
  "user":38,
  "melding":13
  },
  {  
  "id":7,
  "title":"T. test",
  "desc":null,
  "start":"14-2-2018 08:30:00",
  "end":"21-2-2018 17:00:00",
  "user":63,
  "melding":10
  },
  {  
  "id":8,
  "title":"K. Keesen",
  "desc":null,
  "start":"16-2-2018 08:30:00",
  "end":"23-2-2018 17:00:00",
  "user":28,
  "melding":14
  },
  {  
  "id":9,
  "title":"K. Keesen",
  "desc":null,
  "start":"14-2-2018 08:30:00",
  "end":"",
  "user":33,
  "melding":12
  },
  {  
  "id":10,
  "title":"K. Keesen",
  "desc":"fvghbj",
  "start":"22-2-2018 08:30:00",
  "end":"",
  "user":15,
  "melding":11
  },
  {  
  "id":11,
  "title":"K. Keesen",
  "desc":null,
  "start":"15-2-2018 08:30:00",
  "end":"22-2-2018 17:00:00",
  "user":15,
  "melding":1
  },
  {  
  "id":12,
  "title":"K. Keesen",
  "desc":null,
  "start":"23-2-2018 08:30:00",
  "end":"",
  "user":15,
  "melding":1
  },
  {  
  "id":13,
  "title":"K. Keesen",
  "desc":"Test take #25",
  "start":"7-2-2018 08:30:00",
  "end":"23-2-2018 17:00:00",
  "user":15,
  "melding":1
  },
  {  
  "id":14,
  "title":"K. Keesen",
  "desc":null,
  "start":"8-2-2018 08:30:00",
  "end":"",
  "user":15,
  "melding":1
  }
]

我不是很擅长AJAX,所以我敢打赌,我看不到错误,这是我的剧本:

<script>
    $(document).ready(function () {

        GenerateCalendar();

        function GenerateCalendar() {
            $("#calendar").fullCalendar({
                theme: true,
                header: {
                    left: "prev,next today",
                    center: "title",
                    right: "month,agendaWeek,agendaDay"
                },

                defaultView: 'month',
                selectable: true,
                selectHelper: true,
                editable: true,
                eventLimit: true,
                events: function (start, end, callback) {
                    $.ajax({
                        type: "POST",    //WebMethods will not allow GET
                        url: '@Url.Action("List/medewerker_melding")',   //url of a webmethod - example below
                        data: "",  //completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (doc) {
                            var events = [];   //javascript event object created here
                            var obj = JSON.parse(doc);  //.net returns json wrapped in "doc"
                            console.log(obj); //Shows a correct JSON format in the console
                            //jQuery.parse.JSON(obj); //This gives an error: Cannot read property 'JSON' of undefined
                            $.each(doc, function (index, obj) {
                                events.push({
                                    title: obj.title,
                                    start: obj.start,
                                    end: obj.end
                                });
                            });
                            callback(events);

                            $('#calendar').fullCalendar('renderEvent', events, true);
                        }
                    });
                },

                select: function (start, end) {
                    var start = moment(start).format();
                    var end = moment(end).format();
                    $('#startDate').val(start);
                    $('#endDate').val(end);
                    $('#eventModal').modal();
                    if ($('#eventModal')) {
                        $(".meldingForm").submit(function () {
                        });
                    }
                    $('#calendar').fullCalendar('unselect');
                },
            });
        }
    });
</script>

这是将请求发送到的控制器:

    [HttpPost, ActionName("List")]
    [WebMethod(EnableSession = true)]
    public ActionResult List()
    {
        temphrmEntities db = new temphrmEntities();
        List<medewerker_melding> eventList = db.medewerker_melding.ToList();

        // Select events and return datetime as sortable XML Schema style.
        var events = from ev in eventList
                     select new
                     {
                         id = ev.ID,
                         title = ev.medewerker.voorvoegsel + ". " + ev.medewerker.achternaam,
                         desc = ev.Omschrijving,
                         start = ev.datum_van.ToString(),
                         end = ev.datum_tot.ToString(),
                         user = ev.medewerkerID,
                         melding = ev.meldingID
                     };

        // Serialize to JSON string.
        JavaScriptSerializer jss = new JavaScriptSerializer();
        String json = jss.Serialize(events);
        Debug.WriteLine("Json:"+json);
        return Json(json, JsonRequestBehavior.AllowGet);

    }

对于那些想尝试重现问题的人,这是我的HTML和一些额外的脚本:

<div class="modal fade" id="eventModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title" id="exampleModalLabel">Creëer agenda item</h3>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <span id="verplicht">Velden met <i class="fa fa-exclamation-triangle" aria-hidden="true"></i> bent u verplicht in te vullen</span>
        <form class="meldingForm" role="form" action="@Url.Action("Create", "medewerker_melding")" method="post">
            @Html.AntiForgeryToken()
            <div class="modal-body">
                <p><label for="werknemer">Werknemer:</label>@Html.DropDownList("medewerkerID", null, htmlAttributes: new { @class = "form-control ddL" })</p>
                <p><label for="titel">Titel:</label>@Html.DropDownList("meldingID", null, htmlAttributes: new { @class = "form-control ddL" })</p>
                <p><label for="start"><i class="fa fa-exclamation-triangle triangle" aria-hidden="true"></i>Start:</label><input name="startDate" id="startDate" type="date" class="form-control" onmousedown='return false;' readonly required /><input name="start" id="start" class="form-control time" required /></p>
                <p><label for="end">Eind:</label><input name="endDate" type="date" class="form-control" /><input name="end" id="end" class="form-control time" /></p>
                <p><label for="Omschrijving">Omschrijving:</label><textarea type="text" name="Omschrijving" id="Omschrijving" class="Omschrijving form-control" placeholder="Omschrijving" maxlength="200"></textarea></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save changes</button>
            </div>
        </form>
    </div>
</div>

 $(document).ready(function () {
            //zorgt ervoor dat de KendoTimePicker de juiste opties weergeeft.
            $('#start').kendoTimePicker({
                format: "HH:mm",
                min: "8:00",
                max: "17:30",
                value: "8:30",
                interval: 15
            });

            $('#end').kendoTimePicker({
                format: "HH:mm",
                min: "8:00",
                max: "17:30",
                value: "17:00",
                interval: 15
            });
        })

修改

我在ajax中更改了一行来从doc字符串中创建一个对象,我意外地将其保留在那里。现在输出是这样的:

JSFIDDLE(出于某种原因,它不会进入代码块)

谢谢!

编辑可能的重复 这不是与该问题重复的原因是因为我的代码中只有错误导致了这些错误。我的控制器已经在解析一个对象了。

所以我的doc不是一个对象,这不是问题;因为它是。

2 个答案:

答案 0 :(得分:1)

感谢@ Evk的帮助,我们发现我在

中错过了一个参数

events: function(start, end, timezone, callback)

应该是

var obj = JSON.parse(doc);

var obj = doc;现在也是// Serialize to JSON string. JavaScriptSerializer jss = new JavaScriptSerializer(); String json = jss.Serialize(events); Debug.WriteLine("Json:"+json); return Json(json, JsonRequestBehavior.AllowGet); 因为它导致它试图从对象中创建一个对象

最后在我的控制器中,下面的脚本导致了双序列化。

return Json(events, JsonRequestBehavior.AllowGet);

删除序列化并将其更改为[HttpPost] public void saveRecords(Dictionary<string, object> payload) { var _records = this.IRepository.records.Where(w => /*some conditions*/); foreach (var kvp in payload) { var _record = _records.Where(w => w.key == kvp.Key).FirstOrDefault(); if (_record != null) { AutoMapper.Map(kvp.Value, _record); } } this.IRepository.SaveChanges(); } 修复了错误。

由于Evk没有发布答案,我有。

谢谢Evk!

答案 1 :(得分:0)

在运算符中只能应用于对象。不是字符串或基本类型。