javascript 如何将 PHP 字符串变量从 Onclick 事件传递给 JS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8511709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:39:49  来源:igfitidea点击:

How to Pass PHP String Variable To JS From an Onclick Event

phpjavascriptfunctionvariables

提问by user175328

This might have a simple answer, however I cannot figure out the correct syntax. I have the following onclick event echoed on a php page:

这可能有一个简单的答案,但是我无法弄清楚正确的语法。我在 php 页面上回显了以下 onclick 事件:

$ratelink = text string...
echo '<div><span id="anything" onclick="updatePos('.$ratelink.')">Save</div>';

On my JS page, I have the function:

在我的 JS 页面上,我有以下功能:

function updatePos(ratelink)
{
  alert(ratelink); 
}

My problem is that when $ratelink is a number, the variable will pass with no problems. However, when $ratelink is a text string, like in the above example, nothing gets passed and the alert doesn't execute.

我的问题是,当 $ratelink 是一个数字时,变量将毫无问题地通过。然而,当 $ratelink 是一个文本字符串时,就像上面的例子一样,没有任何东西被传递,警报也不会执行。

I think the following ('.$ratelink.') needs to be in a different syntax to pass text, but I don't know the exact format.

我认为以下 ('.$ratelink.') 需要使用不同的语法来传递文本,但我不知道确切的格式。

回答by Ryan LaBarre

You need to enclose the string in quotes when passing to the JS function, as well as in PHP:

传递给 JS 函数和 PHP 时,您需要将字符串括在引号中:

$ratelink = 'text string...';
echo '<div><span id="anything" onclick="updatePos(\''.$ratelink.'\')">Save</div>';

回答by Kashif Khan

try this echo '<div><span id="anything" onclick=updatePos("'.$ratelink.'")>Save</div>'; if there is space in the $ratelink variable then it should be quoted in string....

'<div><span id="anything" onclick=updatePos("'.$ratelink.'")>Save</div>'; 如果 $ratelink 变量中有空格,请尝试此回显,则应在字符串中引用它....

回答by Ben D

Your string needs to be wrapped in quotes... so you'll need to make it

你的字符串需要用引号括起来......所以你需要让它

echo '<div><span id="anything" onclick="updatePos(\''.$ratelink.'\')">Save</div>';

and make sure that you escape the string as well if it might have any quotes in it

并确保您对字符串进行转义,如果它可能有任何引号

回答by Gajus

Neither of the answers are correct. At least not the best option. Consider using json_encode()to pass any data from PHP to JS. This ensures that data is correctly escaped.

两个答案都不正确。至少不是最好的选择。考虑使用json_encode()将任何数据从 PHP 传递到 JS。这可确保正确转义数据。

var myObj = <?=json_encode(array('php' => 'array'))?>;

console.log(myObj);