即使在逃避之后,Quote也会破坏语法

Not*_*ion 1 javascript php yii2

我有一个按钮,应该使用2个参数(一个整数和一个字符串)调用一个动作.我正在使用Yii2.

<button class="button_answer" 
    onclick="submitAnswer(
            <?php echo $id ?>, 
            <?php echo '\''.Html::encode($title).'\''?>
    );">
    Submit your answer
</button>  
Run Code Online (Sandbox Code Playgroud)

它正在工作,但是当参数标题包含单引号双引号时,语法就会被破坏.

我成了这样的事情:

<button class="button_answer" onclick="submitAnswer(214, 'What's the ...?');">
     Post your answer
</button>
Run Code Online (Sandbox Code Playgroud)

我不知道如何解决这个问题.

Que*_*tin 5

您需要为JavaScript编码PHP字符串.然后,您需要为HTML编码JavaScript.

<?php
$js_string_title = json_encode($title);
$js = "submitAnswer($id, $js_string_title)";
$html_safe_js = htmlspecialchars($js);
?>

<button class="button_answer" 
     onclick="<?php echo $html_safe_js; ?>">
  Submit your answer
</button>  
Run Code Online (Sandbox Code Playgroud)

一个更好的方法是避免完全内联JS:

<button class="button_answer" 
        data-id="<?php echo htmlspecialchars($id); ?>"
        data-title="<?php echo htmlspecialchars($title); ?>">
     Post your answer
</button>
Run Code Online (Sandbox Code Playgroud)

以及类似的东西:

addEventListener("click", answer_handler);

function answer_handler(event) {
     var el = event.target;
     if (el.classList.contains("button_answer")) {
         submitAnswer(el.dataset.id, el.dataset.title);
     }
}
Run Code Online (Sandbox Code Playgroud)