2011-04-20 139 views
1

我有一個inArray函數的問題不知道爲什麼。我從我的PHP傳遞一個字符串回到Javascript它看起來像這樣22,24等。我試過使用split命令將它轉換爲一個Javascript數組,我試過它。無論哪種方式,inArray函數沒有找到22,我已經嘗試了22,在inArray函數中使用和不使用標記。

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

      } 

     }); 

謝謝你的任何幫助,這真的讓我瘋狂!

+0

我剛剛重新閱讀你的問題,你提到試圖搜索'「22」'已經所以我刪除了我的答案。請提供'console.log(msg);'的結果,以便我們可以看到傳遞了哪些數據。在您嘗試分割之後,還請顯示數據和代碼。 – Treffynnon 2011-04-20 09:01:28

+0

你可以發佈你的查詢輸出嗎? – alexl 2011-04-20 09:02:26

+0

測試返回什麼值? – 2011-04-20 09:02:52

回答

1

因此從您的評論看,問題是在字符串中的數字22之前有空格([" 22", "24"])。

您可以運行:

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

的工作示例,請參見http://jsfiddle.net/KAdRD/

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/

+0

準確地說,它需要轉換爲數組之前,你問它,如果它在哪裏! :) – 2011-04-20 09:07:11

+0

我沒有使用這個,但無論如何謝謝你! – flyersun 2011-04-20 09:28:03

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

      } 
     }); 

或者類似的東西

如果你不想要搜索字符串值必須拆分味精字符串數組和搜索新成立的陣列來代替。

+0

謝謝你完美的作品,如果我搜索一個字符串或一個數組,只要我得到我想要的結果,我不會感到困擾。 – flyersun 2011-04-20 09:24:24

+0

@Trikks @flyersun。嗯,但是如果你的論點中有222或221的數字呢?上面的代碼將匹配它並且返回true,即使22實際上不在字符串中。請參閱:http://stackoverflow.com/questions/5727813/inarray-issues-with-passing-string-from-php-script/5727852#5727852 – Treffynnon 2011-04-20 09:27:06

+0

@Trikks你不需要在你的正則表達式中的「我」修飾符辦法。數字不區分大小寫。 – Treffynnon 2011-04-20 09:28:01

1

我嘗試了這一點,這將返回1匹配,-1表示不匹配:

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

我猜你的返回類型可能不是一個字符串?就像評論說的嘗試記錄變量或可能typeof

+0

by return type我的意思是** typeof ** ** msg **變量可能不是字符串。另一種可能是你可能會在字符串周圍出現空白字符,你可能會導致意想不到的結果 – redroot 2011-04-20 09:09:27

+0

感謝提示鍵入字符串,所以我不知道它爲什麼不起作用。我現在排序它 – flyersun 2011-04-20 09:25:59

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... 
} 

或有任何需要,從味精陣列的?然後我建議使用純JS的split()函數:

test = msg.split("."); 

然後您可以撥打$.inArray()

+0

排序問題之前,我得到嘗試這種解決方案,但謝謝你的迴應。 – flyersun 2011-04-20 09:26:40

+0

沒問題...試圖幫忙:] – shadyyx 2011-04-20 09:28:34