开发者

Can't parse JSON with JQuery autocomplete

开发者 https://www.devze.com 2023-02-16 02:03 出处:网络
I\'m trying to create an autocomplete text box using VB .Net4.It has a json back-end that simply returns a first name and last name, like so:

I'm trying to create an autocomplete text box using VB .Net4. It has a json back-end that simply returns a first name and last name, like so:

{"d":"[{\"firstN\":\"john\",\"lastN\":\"doe\"},{\"firstN\":\"another \",\"lastN\":\"dude\"},{\"firstN\":\"dsaf\",\"lastN\":\"asdfasdf\"}]"}

My JQuery seems like a pretty standard bit of code:

$("#MainContent_autocomplete").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "/PatientLookup.asmx/LookupPatient",
                        dataType: "json",
                        type: "POST",
                        data: "{ 'key': '" + request.term + "' }",
                        contentType: "application/json; charset=utf-8",
                        processData: true,
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {                                
                                    label: item.firstN,
                                    value: item.firstN
                                }
                            }));
                        }
                    });
                },
                minLength: 2
            });

The problem occurs in the success function. When it gets inside the map function it simply will not let me read the firstN and la开发者_运维问答stN data.


Judging by the quoted array, it looks like you're returning a string value that you've manually JSON serialized using JavaScriptSerializer or DataContractJsonSerializer, like:

public string LookupPatient(string key) {
  // Something that returns a string of JSON here.
}

Is that right?

If so, you should let .NET handle the serialization for you. Like this:

public class Name {
  public string firstN { get; set; }
  public string lastN { get; set; }
}

public List<Name> LookupPatient(string key) {
  List<Name> result = new List<Name>();

  result.Add(new Name() { firstN = "Dave", lastN = "Ward" });
  result.Add(new Name() { firstN = "John", lastN = "Doe" });

  // JSON serialization happens automatically here.
  return result;
}

If you already have an appropriate view model or DTO class, obviously you can reuse that instead of creating the Name class specifically for this one method.


Your JSON is invalid: d's value must not be quoted, and you're escaping the quotes:

{
    "d": [
        {
            "firstN": "john"
            , "lastN": "doe"
        }
        , {
            "firstN": "another"
            , "lastN" : "dude"
        }
        , {
            "firstN": "dsaf",
            "lastN": "asdfasdf"
        }
    ]
}
0

精彩评论

暂无评论...
验证码 换一张
取 消