jquery ajax call return JSON parsing error

前端 未结 5 1284
走了就别回头了
走了就别回头了 2020-12-30 23:14

I am using jquery to call an ajax wcf method that returns a list of objects as a JSON string. The JSON string looks like this when inspecting it in fiddler2 (in TextView):

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-30 23:55

    I've found a workaround:

    The first problem was the circular reference exception on the entity model. To overcome this I use the following code to Detach my entities from the context and then serialize them to strings. I then serialize them on the client using the code below that.

    Service

        [WebGet(ResponseFormat = WebMessageFormat.Json)]
        [OperationContract]
        public string[] GetPeople(Guid groupId)
        {
            using (SchedulerContext context = new SchedulerContext())
            {
    
                var people = (from p in context.People
                              where p.Group_ID == groupId
                              select p).ToList();
    
                JavaScriptSerializer ser = new JavaScriptSerializer();
                string[] result = new string[people.Count];
                for (int i = 0; i

    Client

            $.ajax(
                    {
                        type: "GET",
                        //dataType: "application/json",
                        //dataType: "text/plain",
                        contentType: "json",
                        data: { groupId: 'ae09a080-5d7c-4e92-9a87-591574b7c4b8' },
                        //data: { groupId: 'test' },
                        //data: { groupId: '739526F1-7C58-4E3B-97D8-4870948BFE32' },
                        url: "WebAPI.svc/GetPeople",
                        error: function (jqXHR, textStatus, errorThrown) {
                            alert(jqXHR.resultText);
                        },
                        success: function (people) {
                            //the returned param "people" is of type string[], so each string needs parsed 
                            $(people).each(function (index, value) {
                                var person = $.parseJSON(value);
                                //now I can use the Person object
                            });
    
                        }
                    }
    
            );
    

提交回复
热议问题