如何循环jQuery AJAX请求返回的分隔字符串 [英] How to loop through delimited string returned by jQuery AJAX request

查看:244
本文介绍了如何循环jQuery AJAX请求返回的分隔字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,以下jQuery将一些值发布到PHP脚本并返回逗号分隔的字符串:

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 value of the delimited string is used to toggle a class on/off:

$("#id_"+delimitedvalue).toggleClass("off on");
element.toggleClass("off on");

结果是,如果AJAX,页面上的整批元素都会一起打开/关闭请求成功。

The result is that a whole batch of elements on the page are toggled on/off together if the AJAX request was successful.

但我无法使代码生效。我不知道如何将返回的分隔值赋给toggle函数。另外我怀疑有更好的方法可以做到这一点,并希望听到任何想法!

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");
        }
    }
});

另外,如果你给我们一个 changetags的例子,我们可以提供更多帮助.php 正在回复......

Also, we could help more if you gave us an example of what changetags.php is responding with...

这篇关于如何循环jQuery AJAX请求返回的分隔字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆