pass string with spaces into javascript
i'm trying to pass a php defined string with spaces to a javascript function, so that i can append to a query string. However, the function only works when there are NO spaces, and does not even execute when there are spaces -- by testing with alert().
is there a way I can pass strings with spaces into javascript functions, so that i can eventually do an escape(), and then append to my query string? (using alert() in this example)
.php file
<a onClick=showUser('<?php echo $stringwithspaces; ?>')>click here</a>
.js file
function showUser(str)
{
alert (str);
}
if I could only do something like... onClick=showUser(escape('<?php echo $deptname; ?>'))
... that would be awesome, but that didn't work. Any help woul开发者_运维问答d be much appreciated! Thanks!
The problem is you didn't quote the attribute value. You can leave quotes off of attribute values only if the value doesn't contain spaces, otherwise the HTML processor can't tell when an attribute ends. Even so, it's not recommended; you should always quote HTML attributes.
<a href="showUser('<?php echo addslashes($username) ?>')">user</a>
should work. The call to addslashes
escapes quotes, which would otherwise cause another problem (ending the attribute or string argument of showUser
too soon).
Yes you can you are missing " in you xml attribute field: Each attribute must have a starting and an ending "
myField=
"blabla ...
"
onClick="showUser(escape('<?php echo $deptname; ?>'))"
Try the Unicode escape sequence for a space character, '\u0020'.
精彩评论