简体   繁体   中英

How can I pass a PHP array as an argument to a JavaScript function

It's just an example, but with this code, it works. But if I change 5 to "5" and 10 to "10" I got an Unexpectid ending syntax error for the echo line

PHP

$array = array();
$array[0] = 10;  
$array[1] = 5; 
$json = json_encode($array);

echo "<td style=\"background: red;\"><button onclick=\"modifyModalContent('$day_date_column','$i',$json) ... (really long line)

JS

function modifyModalContent(date, id, array) {
  var header = document.querySelector(".modal-header");
  var body = document.querySelector(".modal-body");

  var table =
  `
  <table class="table table-bordered table-hover">
    <tr>    
      <td>${array[0]}<td>
      <td>${array[1]}<td>
    </tr>
  </table>
  `;

  body.innerHTML = table;

  header.innerHTML = `<h1> Date: ${date}</h1></br><h1>ID: ${autoid}</h1>`;
}

The two echo line after run:

That works:

<tr style="height: 137px;"><td style="background: red;"><button onclick="modifyModalContent('2019-01-21','1',[10,5])" ... (long line) 

And if I use it with a string array got error on this:

<tr style="height: 137px;"><td style="background: red;"><button onclick="modifyModalContent(2019-01-21,1,["10","5"])" ... (long line) 

How could I do the same with an array like this:

$array = array();
$array[0] = "10";  
$array[1] = "5"; 

I guess the problem is because of the " char, but How could I fix it?

我建议使用PHP函数htmlspecialchars -不仅要解决引号问题,还应解决在用作HTML属性值之前应转换为HTML实体的任何其他字符(&,<,>}。

$json = htmlspecialchars(json_encode($array));

Replace ["10","5"] with ['10','5']

More information about simple and double quotes: When to use double or single quotes in JavaScript?

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