ASP.NET AJAX returning JSON but not recognised as JSON

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-06 03:50:07

问题


I have this function to get me back a list of managers

function getManagers() {
   var jqxhr = $.ajax({
                   type: 'POST',
                   contentType: "application/json; charset=utf-8",
                   url: '/webservice.asmx/GetManagers',
                   dataType: 'json'
               }).success(function(data) {
                   var options = '<option selected="selected" disabled="disabled">Select Manager</option>';
                   for (var i = 0; i < data.length; i++) {
                       options += '<option value="' + data[i].PostRef + '">' + data[i].Description + '</option>';
                   }
                   $('#ReceivingCellManager').html(options);
               }).error(function(data) {
                   $('.ErrorText').html('Manager load failed please refresh page with F5');
                   $("#errormessage").dialog('open');
               }).complete(function() {
           });
} 

as you can see I am using JQuery and want to popoulate a drop down list with the available managers

the method within my service looks like this

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void GetManagers()
    {
        using (var context = new ConcessionModel())
        {             
            var rcm = Business.GetManager();
            var serializer = new JavaScriptSerializer();
            var response = rcm.Count() != 0
                ? serializer.Serialize(rcm)
                : serializer.Serialize(new Error { Code = "500", Message = "Manager Retrieval Failed" });
            this.Context.Response.Clear();
            this.Context.Response.ContentType = "application/json";
            this.Context.Response.Write(response);
        }
    }

When the method is called I recieve a response of 200 OK and the response contains the JSON I want the problem I am having is that the response is not being recognised as JSON.

I HAVE TRIED

  • adding dataType to the ajax call as you can see above
  • removing this.Context.Response.flush from the end of the response, this cured an error I was getting with adjusting headers after they were sent.
  • adding a response format to the method
  • adding a Response.ContentType to the Context These have all failed to get me the required recognition of the JSON. Any help would be much appreciated.

UPDATE: JSON FORMAT

{"Description":"data","Code":"data","reference":"data"}

UPDATE JSON RESPONSE I am seeing something weird in the response my response is as follows

[{"Description":"data","Code":"data","reference":"data"}]{"d":null}

I am not sure what the d null object is


回答1:


In order to access the json object such as an object of class 'Dog' from the service, the method return type should be 'Dog'. Do not use response.write in services. You can then access the data from the success message using 'data.d'.

Hope this helps!




回答2:


resolved the issue by removing the contentType from the ajax request and adding settings to the web config as described in this post Request format is unrecognized for URL unexpectedly ending in

Thanks for all your help 1 ups all round :)




回答3:


Try to parse it as i have shown below , it works for me:

var result = JSON.parse(data, function (key, value) {
                    var type;
                    if (value && typeof value === 'object') {
                        type = value.type;
                        if (typeof type === 'string' && typeof window[type] === 'function') {
                            return new (window[type])(value);
                        }
                    }
                    return value;
                });

And change the data to result:

for (var i = 0; i < result.length; i++) {
                       options += '<option value="' + result[i].PostRef + '">' + result[i].Description + '</option>';
                   }



回答4:


In the success function, the return object is 'data'.

In order to access the json data you need to access it via 'data.d'.

I cant help but notice that your web service does return void, maybe that could also be why there is no response??




回答5:


This worked for me:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HelloWorld() {

    JavaScriptSerializer serializer = new JavaScriptSerializer();

    string strResponse = serializer.Serialize("World"); ;

    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.AddHeader("content-length", strResponse.Length.ToString());
    Context.Response.Flush();

    Context.Response.Write(strResponse);


}


来源:https://stackoverflow.com/questions/9939548/asp-net-ajax-returning-json-but-not-recognised-as-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!