4

This is my first JQuery experience and I'm on quite a tight deadline. It's a bit of an embarrassing question, but here goes. I'm calling a web service that returns a list of strings (which works and returns OK). Code is below

$(document).ready(
    function() 
    {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "CatList.asmx/GetCatergoies",
            data: "{}",
            dataType: "json",
            success: onActionCompleted
        });
    }
)

function onActionCompleted(data) {

    var resultData = data['d'];
    alert(resultData);
 }

The alert produces a comma seperate string of the results from the web service. I can't figure out for the life of me how I can iterate through the results. When I do something like this:

resultData.each(
   alert(this)
)

All I get in Firebug is this error:

resultData.each is not a function

Any pointers ?

Jon Jones
  • 1,014
  • 1
  • 9
  • 17

4 Answers4

8

Using Array.split() will produce an array:

var string = "red,blue,green,orange"

$.each(string.split(','), function(){
  alert(this)
})
duckyflip
  • 16,189
  • 5
  • 33
  • 36
5

Consider string.split() instead of jQuery:

var items = results.split(',');

for( var i = 0; i < items.length; i++ ) {
  alert( items[i] );
}
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Program.X
  • 7,250
  • 12
  • 49
  • 83
4

Sounds like your webservice gave you a csv-string. Split it into an array, wrap jQuery around it and add a callback function for each of the elements like this:

$(resultData.split(",")).each(function () {
    alert(this);
});
Magnar
  • 28,550
  • 8
  • 60
  • 65
  • each does also work on normal arrays. So $.each(resultData.split(","), function(){}); should work also. – Ikke May 28 '09 at 11:31
  • Indeed, I just prefer the $(array).each(callback) syntax over $.each(array, callback) for readability purposes. – Magnar May 28 '09 at 11:35
2

Thanks! I wouldn't have been able to solve it without the feedback. I'm still not completely sure what format resultData is. I did some copy and paste on the code so not sure what data['d'] converts the list into in json terms.

When I tried the split on resultdata I got this error in Firebug:

resultData.split is not a function

In the end I just used the $.each() on resultdata without the split and it worked.

function onActionCompleted(data) {

    var resultData = data['d'];
    $.each(resultData, function() {
        alert(this)
    })
}
Jon Jones
  • 1,014
  • 1
  • 9
  • 17
  • This means that data['d'] is already an array :). How did you came up with the idea that it's a comma delimited string ? – duckyflip May 28 '09 at 11:50
  • because alert(resultData); displayed a command delimited string. That must be how javascrip formats arrays? – TizzyFoe Feb 28 '13 at 00:03