2010-07-20 16 views

回答

1

沒有什麼可以做客戶端的,你需要清理服務器上的字符串。鑑於你正在通過<%=%>將字符串放入字符串構造函數,我假設你正在使用各種ASP.Net。

我確定有一個更優雅的方法來做到這一點,但這應該作爲第一次編碼字符串以用於JavaScript。這並沒有試圖解決首先將任意字符串傳遞給JavaScript的相對優點。 (在大多數情況下,應該有很大可能是惡意字符串一些服務器端的檢查。)

假設需要注意的是文本輸入字段,這樣的事情可能會奏效....

// New Property in your code behind 
public string outputText {get; private set;} 

在的OnLoad(),添加

// Encode the string 
string tempText = Note.Text 
outputText = String.empty; 
foreach(char character in tempText) 
{ 
    // Prefix quotation mark with a backslash, 
    if(char == "\"") 
    outputText += "\\\""; 
    // Prefix apostrophe with a backslash, 
    else if(char == "'") 
    outputText += "\\'"; 
    // convert newline to a literal. 
    else if(char == "\n") 
    outputText += "\\n"; 
    else 
    outputText += character; 
} 

最後,在.aspx

var str = new String('<%= outputText %>') 
1

你不能向JS中扔任意文本,並且能夠從錯誤中恢復。

必須在將數據放入文檔之前對數據進行清理。我不知道爲什麼你認爲你不能這樣做,但你需要消除任何阻礙它的障礙。

相關問題