0

I have made a ajax call to java servlet from where i am retrieving data and storing on success in data ..Here is my code...

            var s1="";
            var ticks ="";
            $('#view').click(function(evt){
                alert('hi');
                evt.preventDefault(); 
                $.ajax({
                        url:'getdata',
                        type: 'GET',
                        success: function (data) {
                              console.log(data);
                              alert(data);
                        }

                    });

            });

Here is the values in data on success..

[239, INCOMING, 30, INETCALL, 7, ISD, 55, LOCAL, 44, STD]

Now as per my need i want this value to be in the variables..

s1=239,30,7,55,44 and tics=INCOMING,INETCALL,ISD,LOCAL,STD

Any help will be highly appreciated..

4

3 回答 3

0
var parts = string.split(",")

for (i = 0, l = parts.length; i < l; i += 2) {
    $alert(parts[i]);
}

尝试

于 2013-10-26T08:23:49.880 回答
0

你可以通过它...

<script src="/include/jquery.js"></script>
<script>

var data = [239, "INCOMING", 30, "INETCALL", 7, "ISD", 55, "LOCAL", 44, "STD"]; 

var s1   = [];
var tics = [];

$.each(data,function(i,val)
{ 
    if (i % 2 == 0)
    {
        s1.push(val); 
    }
    else
    {
        tics.push(val); 
    }
});

console.log('s1'); 
console.log(s1);  

console.log('----------');  

console.log('tics'); 
console.log(tics);  

</script>

不过,第一条评论是对的……您能否将接收方式的格式更改为更典型的 JSON 格式?

var data = [ "s1" : { 239, 30, 7, 55, 44 }, "tics" : { "incoming", "isd", "local", "std" } ]; 
于 2013-10-26T08:25:32.243 回答
0

假设您的data变量是一个字符串,即:

"[239, INCOMING, 30, INETCALL, 7, ISD, 55, LOCAL, 44, STD]"

...那么实现所需结果的一种方法是使用然后删除第一个和最后一个字符([]data.slice(1,-1),然后.split()", "你一个这样的数组:

["239", "INCOMING", "30", "INETCALL", "7", "ISD", "55", "LOCAL", "44", "STD"]

然后将每隔一个项目放入不同的数组中,并将.join()这些数组放入您要求的格式的字符串中:

var a = data.slice(1,-1).split(", "),
    s1 = [],
    tics = [],
    i = 0;
while (i < a.length) {
    s1.push(a[i++]);
    tics.push(a[i++]);
}
s1 = s1.join(",");
tics = tics.join(",");

我不明白为什么您想要的结果是包含逗号分隔字符串的值的变量。显然我不知道你想要实现什么,但对我来说,如果数组将这些值作为单独的元素保存更有意义s1tics在这种情况下,你显然会省略.join(",")我展示的代码末尾的语句)。但是,如果您可以更新服务器端进程以返回 JSON 格式,则可以返回如下内容:

{
    "s1" : [239, 30, 7, 55, 44],
    "tics" : ["INCOMING", "INETCALL", "ISD", "LOCAL", "STD"]
}

...然后 jQuery 会为您解析 JSON,让您将其作为对象处理,其属性已设置为数组。

于 2013-10-26T08:26:23.983 回答