2016-07-15 5 views
1

JavaScriptの関数に文字列パラメータを送信していますが、問題はスペース文字や引用符です。私はどちらか一方を働かせることができますが、両方の方法を同時に働かせる方法を見つけることはできません。パラメータのエンコーディング(引用符と空白文字)

私は現在、スペースを扱うためにencodeURIComponentとdecodeURIComponentを使用しています。

Javascriptを:

function alertTitle(title){ 
    alert(decodeURIComponent(title)); 
} 

PHP:

//...fetching from MySQL 
$title = $row['title']; 

//If $title content is wrapped in single or double quotes, this will do: 
$title = str_replace("\"",""",$row['title']); 
//But if it's not, and has spaces, I have to wrap it in quotes for encodeURIComponent: 
$title = '\''.$row['title'].'\''; 
//And that obviously gives error in encodeURIComponent if $title happens already to have 
// single quotes 

//..And sending $title to javascript: 
echo '<a onclick="alertTitle(encodeURIComponent('.$title.'));" href="#">Alert</a>'; 

だから何とか私はまた、単一引用符をエスケープするか、そしていくつかの非常に異なるアプローチを思い付くする必要があります。 これはすでに近いので、私は単純なものを逃してしまったと思う。

"タイトル"

"スペースでタイトル" すべての組み合わせ」と

'タイトル'

'タイトル':

$のタイトルは以下の例のanykindかもしれない

タイトル「Blaablaa」はこちら

など。

すべてのヒントは大歓迎です。ありがとう!

+1

'エコーjson_encode($タイトル)を追加し、必要であれば、同様)(はhtmlspecialcharsを通じてこれを実行します。 –

+0

ありがとうMarc!両方を使って仕事を完璧にやった!ちょっと、いかがですか! – kaarto

答えて

0

ただ、 `単一引用符を使用して事前に交換してください:)

//...fetching from MySQL 
$title = $row['title']; 

//If $title content is wrapped in single or double quotes, this will do: 
$title = str_replace("\"","&quot;",$row['title']); 
$title = str_replace("\'","&#39;",$row['title']); 

//But if it's not, and has spaces, I have to wrap it in quotes for encodeURIComponent: 
$title = '\''.$row['title'].'\''; 
//And that obviously gives error in encodeURIComponent if $title happens already to have 
// single quotes 

//..And sending $title to javascript: 
echo '<a onclick="alertTitle(encodeURIComponent('.$title.'));" href="#">Alert</a>'; 
+0

実際にこの点も試してみましたが、何らかの理由でそれが役に立たなかったのです。 :(幸いにもマークの方法は完璧に働いた – kaarto

関連する問題