Currently, I am dealing with a .each loop that processes an object retrieved from a JSON feed through Ajax (Type: jsonp; the success function sends the "data" to the function/method containing the .each loop).
The issue puzzling me is that when the feed returns multiple sets of data, it parses them correctly. However, if it only returns one set of data, the loop attempts to break down the individual fields of that lone record as if each field were a record itself.
Below are examples of the objects received from the Ajax routine:
Example 1: -- single item
{
"SmeDetail": {
"SipAddress": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cf6fd2ff105efdf4e8fcfe81fdfcfeeb">[email protected]</a>",
"SubjectExpert": "Smith, John",
"SubjectMatter": "JavaScript"
}
}
Example 2: -- multiple items
{
"SmeDetail": [
{
"SipAddress": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0d6c2d7dcd091ddd5ccd3d8d4d390d0d3b0fccbd0fed3dcddc6d0dad195"><em>[email protected]</em></a>",
"SubjectExpert": "Doe, Jane",
"SubjectMatter": "HTML"
},
{
"SipAddress": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="48796474737c646933767270677377697332777365323e737f7d">[email protected]</a>",
"SubjectExpert": "Doe, John",
"SubjectMatter": "CSS"
}
]
}
Now, let's look at the .each routine:
$.each(json_data.SmeDetail, function (i,val){
var sip_address = val.SipAddress;
var SME_name = val.SubjectExpert;
var subject_matter = val.SubjectMatter;
var sip_link = "<a href='sip:" + sip_address +
"'><img src='http://server/prod/images/im.gif' hspace='2' border='0' title='Send an instant message to " +
SME_name + "' alt='Send an instant message to " +
SME_name + "'/></a>";
output7 = output7 + "<tr><td>" +
SME_name + " " + sip_link + "</td></tr>";
});
I inserted some alert statements for verification purposes. When this runs for a single record from the feed, it incorrectly loops three times and assigns "undefined" to all variables. The fact that it loops exactly three times and enters the loop indicates that it recognizes a "SmeDetail" record but treats each individual field as a separate record.
This makes me question the structure of the single-record return. Should there be brackets around that sole item?