简体   繁体   中英

How do i enclose the Single quotes in double quotes in javascript

I have a php variable that needs to be interpreted in javascript how do i do this

var cntr = "<?php echo $j;?>";
var opt = "<?php echo $options;?>";
var opt_selected = "<?php echo get_options($val['SOMEVARIABLE'],$opt); ?>";
var reference = "<?php echo $val["RFDREFVAL"];?>";

How do i correct the above statements iam getting Javascript error "unterminated string contant " .what is the Best to have this php variables interpreted

Try:

var reference = "<?php echo json_encode($val["RFDREFVAL"]);?>";

In the general case, let's say you have a PHP expression you want to put into a Javascript string. Let's call the PHP expression BLAH_BLAH_BLAH. Use:

var my_variable_name = "<?php echo json_encode(BLAH_BLAH_BLAH);?>";

So for example, if your expression is:

StuClass::getopt($val["CDE"],$opt)

then you want:

var my_variable_name = "<?php echo json_encode(StuClass::getopt($val["CDE"],$opt));?>";

It looks like your PHP code is producing output that contains quotes and/or backslashes. Use addslashes to escape these before using them in JavaScript. For example:

var cntr = "<?php echo addslashes($j);?>";

and similarly for the other variables.

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