$ .inArray从php脚本传递字符串的问题

时间:2011-04-20 08:56:09

标签: php jquery

我遇到了inArray函数的问题,不知道为什么。我正在将一个字符串传递给我的PHP中的Javascript它看起来像22,24等。我已经尝试使用split命令将其转换为Javascript数组,我已经尝试过了。无论哪种方式,inArray函数都找不到22,我在inArray函数中尝试了22个带有和不带说话标记的函数。

$.ajax({
           url: "<?=base_url(); ?>/products/update_dropdown/"+<?=$product['product_id']?>+"/"+strUser,
           type: 'GET',
           success: function(msg) {
              var test;
              test = $.inArray(22, msg);
              alert(test);

            }

       });

感谢您的帮助,这真的让我疯了!

5 个答案:

答案 0 :(得分:1)

所以从你的评论中看,问题是你的字符串([" 22", "24"])中的数字22之前有空格。

你可以运行:

msg = msg.replace(/\s/g, '').split(',');
test = $.inArray('22', msg);

有关实例,请参阅http://jsfiddle.net/KAdRD/

答案 1 :(得分:1)

 var test = "22,24,25";

 test = test.split(",")

 test = $.inArray(22+'', test); // explicitly convert search to string.
 alert(test);  // alerts index of found element.

http://jsfiddle.net/s3X8V/1/

答案 2 :(得分:1)

我尝试了这个,这将为匹配返回1,为不匹配返回-1:

    var string = "33,34,35"; 
    var test = $.inArray("34",string.split(","));
    alert(test);

我猜你的回复类型可能不是字符串?就像评论说的那样尝试记录变量或者 typeof

答案 3 :(得分:1)

使用indexOf函数怎么样?如果从PHP到JS的变量集是一个字符串,你可以这样使用它:

if(msg.indexof('22', 0) != -1) {
    // this is the case when 22 is a part of msg...
} else {
    // this is the case when 22 is not present in msg...
}

或者是否需要来自msg的数组?然后我建议使用纯JS split()函数:

test = msg.split(".");

然后你可以拨打$.inArray()

答案 4 :(得分:0)

显然,从php返回的值不是javascript中的数组。它以字符串形式返回。

$.ajax({
           url: "<?=base_url(); ?>/products/update_dropdown/"+<?=$product['product_id']?>+"/"+strUser,
           type: 'GET',
           success: function(msg) {
              var test;
              test = msg.search(/22/i)
              alert(test);

            }
       });

或类似的东西

如果您不想搜索字符串值,则必须将msg字符串拆分为数组并搜索新形成的数组。