简体   繁体   中英

how to access and output json results from $.ajax() success callback

I'm using coldfusion and jquery. This is my first real go at jquery and I've searched and read for a long time without cracking this so any help would be greatly appreciated...

Ok, I have an autocomplete returning an id. I'm then passing the id to a second function that returns an array of datatype json. The autocomplete works great and I can get the json to display in an alert box but am a bit stuck on how to use the json results.

I'm trying to loop through the json array and write the values into radio buttons, which then dynamically display on page... So the whole idea is this.

  1. user is selected from drop box and id is returned
  2. user id from selection is passed to user options function and user options are returned in json arrary.
  3. json array is looped through and on each iteration a radio button is created with appropriate values.
  4. all radio buttons are then output to screen for access and selection.

The code I have so far is this :

<script type="text/javascript">
 // <!--
 $(document).ready(function() {
    $("#userName").autocomplete({
        cache:false,
        source: "/jqueryui/com/autocomplete.cfc?method=getUser&returnformat=json",
        //setup hidden fields
        select:function(event,ui) {
            var uid = ui.item.id;
            $("#userid").val(ui.item.id);


            // start call to get user options
             $.ajax({
                 type: "POST",
                 url: "/jqueryui/com/autocomplete.cfc?method=getUserOptions&returnformat=json",
                 data: ({ userid: uid }),
                 success: function(data) {              
                    alert(data)
                    }
                 });
            /// end call to get user options
        }
    });
});
// --->

</script>

The json displayed in the "alert(data)" popup, which looks fine, is this :

[{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}]

I need to know how to loop through this data and create a radio button for each option, probably something like this, and display them all on screen, which I'm guessing I'll just write to a via the dom once I have something to write :

<input type="radio" name="userOption" value="#id#|#qty#|#term#">#productname#

I have tried a few things, without success, such as :

for(var i =0;i&lt;Data.length-1;i++) 
{ 
  var item = Data[i]; 
  alert(item.productname + item.id); 
} 

And

$.each(data.items, function(i,item){      
    alert(item);      
    if ( i == 3 ) return false;    
    });

I couldn't get either of these to work.

Anyway this is getting a bit long winded. Hope it's clear, and again any help or suggestions appreciated.

Thanks!

First check the datatype of the data parameter returned. You might first need to use .parseJSON() to construct a JSON object.

Then your for loop syntax is not correct. this code works for me:

var data = [{"productname":"licence free","quantity":1,"term":12,"id":1},
            {"productname":"licence basic","quantity":1,"term":24,"id":1},  
            {"productname":"licence full","quantity":1,"term":12,"id":2}];

for (var i=0; i<data.length; i++) {
    alert(data[i].productname);
}

Here's a jsfiddle

尝试检查parseJSON jquery函数。

I quess that the type is a string? If so try it with the javascript function eval. It converts a string to a javascript type.. in your case something like this should work:

Var new_data = eval(data);

Now it should be a workable array/object

Edit: to stay with the data variable:

data = eval(data);

Edit 2:

Your ajax call misses the dataType property:

dataType: "json"

With this you dont need the stuff above i said

Use a each loop to get data and appendTo function to print data in an HTML element with result1 id:

dataType:"json", //nature of returned data
success: function(data) {
    var  content = ''; 

    $.each(data, function(i, dbdata) {
        content += '<p>' + dbdata.columnName + '<p>';
    });

    $(content).appendTo("#result1");
}

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