How to loop through delimited string returned by jQuery AJAX request
So the following jQuery is posting some values to a PHP script and getting back a comma delimited string:
$.ajax({
type: "POST",
url: "_js/changetags.php",
dataType:'json',
success: function(data){
arr = data.tagsinserted.split(',');
$.each(arr, function(n, val){
// toggle here
});
}
});
What I'm trying to do is place the following code into the loop, so that the开发者_JAVA技巧 value of the delimited string is used to toggle a class on/off:
$("#id_"+delimitedvalue).toggleClass("off on");
element.toggleClass("off on");
The result is that a whole batch of elements on the page are toggled on/off together if the AJAX request was successful.
But I can't get the code to work. I don't know how to assign the returned delimited values to the toggle function. Also I suspect there is there a better way to do this and would love to hear any ideas!
I think you are looking for something like this:
$.ajax({
type: "POST",
url: "_js/changetags.php",
dataType:'json',
success: function(data){
var arr = data.tagsinserted.split(',');
for(var i = 0; i<arr.length; i++){
//Bad idea to use .each(), much slower in this case
$("#id_"+arr[i]).toggleClass("off on");
element.toggleClass("off on");
}
}
});
Also, we could help more if you gave us an example of what changetags.php
is responding with...
Have you tried this:
$.each(arr, function(n, val) {
$('#id_'+val).toggleClass('off on');
});
精彩评论