views:

286

answers:

2

I'm making a call to a page method via AJAX in my ASP.NET application via JQUERY's AJAX method e.g.

       $.ajax({
       type: "POST",
       url: "page.aspx/GetDropDowns",
       data: "{'aId':'1'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function(msg) {
         alert(msg.d);
       },
       error: function() {
         alert('Error getting page');
       }

I'll be returning the results in JSON format, whereby I will be populating a drop down. I could do this part myself but I want to know if there is any built in magic in JQuery for processing JSON results or if there are any good utility scripts for this sort of thing.

+1  A: 

There is little jQuery itself can help you with populating dropdown. You just need to create HTML and append it to your dropdown.

I'm not sure what is the format of your data so I'm assuming it's an object where keys should be dropdown's keys and values should be dropdown's values.

I also prefer using $.post then $.ajax as it has a clearer structure for me.

$.post('page.aspx/GetDropDowns', {'aId': '1'}, function (data, status) {
    if (status === 'success') {
        var options = [];
        for (var key in data) {
            options.push('<option value="' + key + '">' + data[key] + '</option>');
        }
        $('#yourId').append(options.join(''));
    } else {
        alert('error');
    }
}, 'json');
RaYell
+1  A: 

In the past I have used a plugin when working with dropdowns.

http://www.texotela.co.uk/code/jquery/select

Request the JSON data:

    //Get the JSON Data
    $.getJSON(url, function(json) {
       PopulateDropDownFromJson(json, "#element");
    });

and then just pass the JSON into a function that uses the plugin above

    function PopulateDropDownFromJson(json, element){
       $.each(json, function() {
       $(element).addOption(this[valueText], this[displayText], false);
    });

}

Nick Clarke