How to pass string to javascript funciton which contains special characters
I have this little php snippet:
// $test='test';
$test='just a test';
echo "<a href=javascript:myfunction($number,$src_req,\"".$test."\")><img style='z-index:$z; src='images/$src'/></a>";
And i have this little ajax snippet...
function myfunction(param1,param2,param开发者_Python百科3)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse2(xmlHttp.responseText);
}
}
var p1=param1;
var p2=param2;
var p3=param3;
xmlHttp.open("GET", "config/ajax_pop.php", true);
xmlHttp.send(null);
$( '#ResponseDiv2' ).dialog({
height: 140,
modal: true,
position: [490,140],
title:param3,
});
.....
I like to pass my $test php variable to my javascript function, but unfortunatelly if my $test variable contain space character then the JS script doesnt work. If my $test variable contain only one word, then work well.
In the browser when i check the link i see:
a, if $test variable contain only one word, then: javascript:myfunction(1,1,"test")
b, if $test variable contain more then one words then: javascript:myfunction(1,1,"just
Thank you for the help...
Use json_encode(): http://php.net/json_encode
Update: Here's a usage example:
<?php
$number = 1;
$src_req = 2;
$z = 3;
$src = 4;
$test = 'just a test
with spaces and new lines';
echo "<a href=javascript:myfunction($number,$src_req," . json_encode($test) .")><img style='z-index:$z; src='images/$src'/></a>";
If it doesn't work, try to find out in what exact way it's not working. A "Does not work" question is as useful as a "Then fix it" answer.
In any case, mixing PHP, HTML, JavaScript and CSS in one single line of code is not worth the effort even for quick testing. Separarte stuff in functions and files you'll make your life easier.
You must wrap the href
itself with double quotes then the value with single quotes:
href=\"javascript:myfunction($number, $src_req, '".$test."')\"
You can escape the string with php function urlencode and can use javascripts unescape to unescape.
you have to parse the third parameter in your js function with unescape ...
as well you can use json as Álvaro G. Vicario mentioned.
精彩评论