开发者

Fetch jquery ajax call into array

I would like to know if it is possible to return the ajax call into a javascript array, rather than a DOM object. The ajax call is returning something like n-tuples of value1-value2, and I would like to iterate over that.

Thanks.

$(function () {
    $("#categoria").change(function() {
        var id = $(this).val();
    开发者_StackOverflow社区    alert(id);
        vars = load("getcategoria.php", "q="+id); // can I do something like this? how?
    });
});


Yes you can do this, but .load() is the wrong method for the job. .load() is used to load HTML into a specific DOM element.

I suggest you have your getcategoria.php return a JSON object (use PHP's json_encode), and then use $.getJSON() to get it, parse it, and use it how you wish.

$.getJSON("getcategoria.php", "q="+id, function(data){
  // data is your JSON object, use it how you wish
});


You can use the jQuery getJSON() method to return a JSON String which you can then iterate over.

This example from the linked page shows how on retrieving a JSON string you then iterate over it and generate a list. YOu can modify this to perform your own iteration and behaviour.

  $.getJSON('ajax/test.json', function(data) {
  var items = [];

 $.each(data, function(key, val) {
   items.push('<li id="' + key + '">' + val + '</li>');
 });

  $('<ul/>', {
   'class': 'my-new-list',
   html: items.join('')
  }).appendTo('body');
});


And dont forget to have set header('content-type: application/json') in your getcategoria.php file

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜