2014-09-01 59 views
-1

我已經搜索了所有其他相關的問題,但沒有更明智的。string.search()拋出一個JavaScript錯誤'對象不支持屬性或方法搜索'

我重新加載表單時使用javascript捕獲表單數據,所以我可以讀取PHP中$ _GET中的數據。

它工作正常,除非在字符串中有'&'。我的意見代碼:

oSupps = form.elements["supps[]"]; 
//a multi-choice select element 
var supps = getSelectedOptions(oSupps); 
//returns a comma-separated list of selected items; this includes the correct string with 
the ampersand 
var params='supps='+supps; 
//sets up the string to be returned to the page in the next line of code 
self.location='instructor_register_2.inc?' + params; 

的URL顯示正確的字符串符號,但$ _GET拆分字符串轉換成2排,失去的符號。

一個例子:

string is "Abercrombie & Fitch" 
$_GET is: 
supps "Abercrombie" 
Fitch "" 

我試圖檢查字符串中的符號,並在使用JavaScript逃避它:

needle=/&/ 
pos=supps.search(needle) 
if(pos!=-1) 
{ 
    newsupps=supps.replace(" & "," /& "); 
    supps=newsupps; 
} 

,但它不會讓過去的supps.search說「該對象不支持屬性或方法搜索」。

我在使用PhpED 8.1版的內置瀏覽器。

我找不到任何引用搜索(也許替換)不支持任何特定的瀏覽器,他們都包含在我可以找到的所有基本的JavaScript教程。

任何想法,請

+1

似乎有一個很好的機會'supps'不是一個字符串。在嘗試搜索之前嘗試添加'console.log(typeof supps)'。我的猜測是'getSelectedOptions()'返回一個數組 – Phil 2014-09-01 01:11:13

+0

你試過編碼你的'params'字符串嗎? 'encodeURIComponent(params)' – Oliboy50 2014-09-01 01:11:49

+0

你可以試試這個'console.log(「Abercrombie」.search(/&/))'讓我們知道輸出嗎? – Dalorzo 2014-09-01 01:12:12

回答

3

您需要通過調用encodeURIComponent逃離URL組件:

var params = 'supps=' + encodeURIComponent(supps); 
+1

即使'supps'是一個數組(它將被轉換爲'encodeURIComponent'中的字符串),這個問題肯定會照顧到這個問題 – Phil 2014-09-01 01:16:14

+0

對不起,encodeURI行給出'undefined'後的警告(params) – steveatootac 2014-09-01 09:04:13

+0

糟糕,把改變後的代碼放在錯誤的地方 - 愚蠢的我。它的工作原理 - 非常感謝。 – steveatootac 2014-09-01 09:17:47

1

您使用GET,所以符號表示屬性的末尾。所以「惠譽」被解釋爲一個新屬性的名稱,它沒有任何價值。運行params = encodeURIComponent(params)以轉義所有URI特定的字符。

相關問題