Can't generate Javascript from data with parentheses
I'm using a PHP/MySQL connection to add a search suggestions feature to my site. It's all working except for one piece. My data all contains parentheses in t开发者_高级运维he values, so when I'm trying to pass the returned data to the input field my onclick function fails! code is as follows:
while ($result = $query->fetch_object()) {
echo '</li><li onclick="fill(\''.$result->name.'\');">'.$result->name.'</li>';
}
The list populates from the returned search results, but the query returned looks like this:
</li><li onclick="fill('Boire Field, Nashua, NH, US (KASH)');">
Boire Field, Nashua, NH, US (KASH)</li>
Firebug gives me the following:
unterminated string literal
fill('Boire Field, Nashua, NH, US (KASH)
The )
in the result is prematurely ending the string. How can I escape this out so it will properly call the function?
As the Brad Suggests.. The best way is JSON_ENCODE
while ($result = $query->fetch_object()) {
echo '</li><li onclick="fill(\''.json_encode($result->name).'\');">'.$result->name.'</li>';
}
精彩评论