开发者

Passing a String from PHP to a JavaScript function

开发者 https://www.devze.com 2023-02-13 09:40 出处:网络
I a开发者_StackOverflowm trying to write a code to pass a PHP string when clicked on the table: <?php

I a开发者_StackOverflowm trying to write a code to pass a PHP string when clicked on the table:

<?php
    echo("<td onclick = 'print_("$file[$i]->Name");' >". $files[$i]->Name."</td>");  
?>

Where files[] is an array, and each element is a class with Name as a string, and it is put in a for loop. I am trying to pass it to a JavaScript function where I need the name there, and it's not working. I tried passing the i variable and it was passed correctly so I thought there should be a special syntax for dealing with strings.

function print_(var x)  {
    alert(x);
}


you need to put quotes around the string. try this:


echo("<td onclick = 'print_(\'".$file[$i]->Name."\');' >". $files[$i]->Name."</td>");

also make sure your $file[$i]->Name doesn't contain quotes


You could write the value and not display it. Then display it when clicked:

echo("<td id='" . $i . "' onclick='javascript:show(" . $i . ")'><p>" . $files[$i]->Name . "</p></td>");

then set the p-tag's visibility to hidden, and show it using the show() function. if this doesn't do it for you i suggest you do it with an ajax call :)


You could try something like this:

<?php
...
$scriptCode="";
...(looping) 

echo("<td id='print_td$i' >". $files[$i]->Name."</td>");
$scriptCode .= '$("#print_td'.$i.'").click(function(){
  var id = '.$i.';
  //Do whatever JS you need to here, possibly: print_(id);
});';

... (end loop)

?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
  <?php echo $scriptCode; ?>
});
</script>

This is a little more extensive, but it will get you more flexibility in the future.


In addition to quoting and concatenating as matei suggested, your function is failing because function print_(var x) is not valid JavaScript. You don't need the var in the function declaration. Just declare it like this: function print_(x)

Good luck.


I had the same problem and found the answer (even though it did not make sense)

You would expect this to work...

echo '<td onclick="showPicture("' . $pic . '")><img src="' . $row['imgRef'] . '" height="60"; /></td>';

but in actual fact, this works...

echo '<td onclick=showPicture(' . $pic . ')><img src=' . $row['imgRef'] . ' height="60"; /></td>';

You will see that you actually have to omit the quotes where you would normally expect to see them.

0

精彩评论

暂无评论...
验证码 换一张
取 消