I have ajax requests in my requests array. The number of requests could be 1,2 or 3 (does not matter, dynamically).
The requests like this:
var ajaxRequest = $.get(ajaxUrl, requestData);
I am want to process the results like this:
$.when.apply($, requests).then(function () {
$.each(arguments, function (key, value) {
console.log(value);
//var response = JSON.parse(value[0]); //It is fail if there is only 1 ajax request
});
});
The problem is the arguments.
If there is only 1 request, than at the each, the values will be
string [the json string, what I want to JSON.parse]
string ['success']
Object [the Ajax request Object]
In this case the arguments length is 3, this will cause problems later.
But, if I have 2 or 3 requests, then I will get back arrays like this, (for example for 2 requests):
Array [json string, 'success', ajax Object],
Array [json string, 'success', ajax Object]
If three requests, of course one more array.
And the problem is here. I can not check the length of arguments, because it is 3 if I have 3 requests, and 3 if I have only one requests.
So I rewrote my script like this:
$.each(arguments, function (key, value) {
if (typeof value === 'string') {
var response = JSON.parse(value);
} else {
var response = JSON.parse(value[0]);
}
$('div[data-id="' + response.productId + '"').find('.dictionaryContainer').find('ul').html(response.html);
});
Now my problem is here:
if (typeof value === 'string') {
even if it is good, the iteration is continuous, maybe it could be hacked somehow with flags, and return tures, but I bet, there is some more elegant solution for this.
Can anybody help me to handle this?
argumentsvariable before the$.each. Now I am working on this.$.eachI check, ifarguments[0]is exists, and if yes, and this is a string, then just 1 request has sent, but if it is an object, I need to use$.each.