![](/img/trans.png)
[英]how to pass array string in JavaScript function from PHP end as a argument?
[英]How can I pass a PHP array as an argument to a JavaScript function
這只是一個示例,但是使用此代碼,它可以工作。 但是,如果我將5更改為“ 5” ,將10更改為“ 10” ,則回顯行出現意外的結尾語法錯誤
的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>`;
}
運行后的兩條回聲線:
這樣可行:
<tr style="height: 137px;"><td style="background: red;"><button onclick="modifyModalContent('2019-01-21','1',[10,5])" ... (long line)
如果我將它與字符串數組一起使用,則會出現以下錯誤:
<tr style="height: 137px;"><td style="background: red;"><button onclick="modifyModalContent(2019-01-21,1,["10","5"])" ... (long line)
我如何用這樣的數組做同樣的事情:
$array = array();
$array[0] = "10";
$array[1] = "5";
我猜問題出在“ char”,但是我該如何解決?
我建議使用PHP函數htmlspecialchars
-不僅要解決引號問題,還應解決在用作HTML屬性值之前應轉換為HTML實體的任何其他字符(&,<,>}。
$json = htmlspecialchars(json_encode($array));
將["10","5"]
替換為['10','5']
有關單引號和雙引號的更多信息: 何時在JavaScript中使用雙引號或單引號?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.