简体   繁体   中英

Using JSON-Object in jqueryUI autocomplete

I'm loading a JSON array from an external Domain. I have gotten this to work correctly yet I am still having problems actually showing any of the results. Using examples and other question/answers I have gotten as far as an attempt of displaying the results apparently being made, but ending in an uncaught error:

Uncaught TypeError: Cannot read property 'label' of undefined

Code snippet:

$('#citySearchBox').autocomplete({
      source: function(request, response){
          $.ajax({
              url: "/api.php",
              data: {action: "search", input: request.term},
              dataType: "jsonp"
          });
          response(function(data){
              return $.parseJSON(data);
          });
      },
      minLength: 3
  });

Server Response as seen in debugger:

[{"id":"1.3.0.0.0.0","label":"Berlin (10115)","value":"index.php?action=city&city=1.3.0.0.0.0"}, etc... ]

As you can see I have attempted to parse the string into a JS Object, with shown method and also tried JSON.parse(data) .

If I've made a mistake earlier than the "response" part but somehow managed to half-way bodge it please point out my mistakes.

EDIT:

I've changed the code after Bradys suggestion, but I seem to be doing something wrong with the syntax, as putting a break-point inside of the response function nothing is stopped.

This is the updated response function:

response( function(data){
        var items = data.text().slice(1, -1).split(',');
        for(i=0; i < (items.length - 3); i=i+3)
        {
            items[i] = $.parseJSON(items[i]) + ','
             + $.parseJSON(items[i+1]) + ',' + $.parseJSON(items[i+2]);
        }
        return items;
    });

Case closed, never actually got JSONP to work, but the situation changed and was no longer reliant on cross-domain communication.

For anybody interested working code is as follows:

  $('#searchBox').autocomplete({
      source: function(request, response){
          $.ajax({
              type: "GET",
              url: "api.php",
              async: true,
              data: {action: "search", input: request.term},
              success: function(data){
                  var items  = $.parseJSON(data);
                  response(items);
              }
          });
      },
      select: function(event, ui){
          $('#searchBox').val(ui.item.value);
          window.location.href = ui.item.url;
      },
      minLength: 2
  });

What you're getting from the server is not a JSON string. It's an array. You should split up the array and parse each object individually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM