简体   繁体   中英

passing special characters to javascript function

I have the following code: opener.postConditionPostCure("<?php echo the_field('cure_description'); ?>")

In some cases the_field() returns ' " ) characters. I believe these characters are throwing errors. I have tried using the js fn escape() function as well as the php fn rawurlencode() as:

opener.postConditionPostCure(escape("<?php echo the_field('cure_description'); ?>"))
opener.postConditionPostCure("<?php echo rawurlencode(the_field('cure_description')); ?>")

to no avail.

I would like the entire string returned by the_field() to be passed to the postConditionPostCure function.

All advice is appreciated. Thanks in advance.

使用PHP函数addslashes()将转义那些导致js混乱的字符。

opener.postConditionPostCure("<?php echo addslashes(the_field('cure_description')); ?>")

This is horrible.

Never ever, ever, ever integrate dynamic output directly into javascript like that.

Read the plethora of reasons why this is a terrible practice here .


But since you're just going to do it anyway, at least encode the JavaScript value properly first.

var json = '<?php echo json_encode(the_field("cure_description"), JSON_HEX_APOS) ?>';

var cureDescription = JSON.parse(json);

opener.postConditionPostCure(cureDescription);

I'm calling json_encode with the JSON_HEX_APOS flag because I'm wrapping the JSON in ' (single quotes) in the JavaScript.


You have two other more ideal options at your disposal though

  1. use ajax to get the value you need
  2. render a <input type="hidden"> and fetch the value using JavaScript.

Both solutions avoid embedding PHP directly in your JS.

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