简体   繁体   中英

passing more than one argument in javascript function

I have a pre-written code in Php where JavaScript function is called

echo "<a href='javascript:submittemplate(".$temprow['templateid'].");'>".$temprow["templatename"]."</a></td>";

and the script is :

  <script>
        function submittemplate(templateid)
        {

            window.document.location.href = 'index.php?module=Users&action=UsersAjax&file=TemplateMerge&templateid='+templateid;

        }
 </script>

Now I wanted to pass one more argument In this function.
What I did was this :

echo "<a href='javascript:submittemplate(".$temprow['templateid'].",".$mode.");'>".$temprow["templatename"]."</a></td>";


<script>
function submittemplate(templateid,mode)
{
alert("anything");
    window.document.location.href = 'index.php?module=Users&action=UsersAjax&file=TemplateMerge&templateid='+templateid;

}
</script>

The Later code does not work. What am I doing wrong ?

if the mode variable is a string this will raise an error.

eg alert(myString Is Here) // throw error

it should be alert("myString Is Here");

so you must add quotation to be like this :

echo "<a href='javascript:submittemplate(".$temprow['templateid'].",\"".$mode."\");'>"

note the \\"

I'll guess that you are producing invalid Javascript syntax because of the values your are outputting. Open your browser's Javascript Console to debug your Javascript and see any errors.

When outputting PHP values to Javascript, you should make sure they won't break the syntax. The best way to do that is to JSON-encode them, since JSON is valid literal Javascript. Just as you should also HTML-encode your values in HTML:

<a href="javascript:submittemplate(<?php echo htmlspecialchars(json_encode($temprow['templateid']), ENT_COMPAT); ?>, <?php echo htmlspecialchars(json_encode($mode), ENT_COMPAT); ?>);"><?php echo htmlspecialchars($temprow["templatename"]); ?></a></td>

Since this is a terribly unreadable one-liner, you should look into binding the onclick event to the link using Javascript, not use a href="javascript:" target. See http://en.wikipedia.org/wiki/Unobtrusive_Javascript#Separation_of_behavior_from_markup .

  1. Do not use the javascript: protocol, use onclick and return false
  2. Why use JavaScript at all???
  <a href="'index.php?module=Users&action=UsersAjax&file=TemplateMerge&templateid=<?PHP echo $temprow['templateid']; ?>">.....

you need to use escaped double quotes around arguments

...submittemplate(\"".$temprow['templateid']."\");'>".

since you're passing strings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM