如何通过Onclick事件将PHP字符串变量传递给JS [英] How to Pass PHP String Variable To JS From an Onclick Event

查看:1557
本文介绍了如何通过Onclick事件将PHP字符串变量传递给JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能有一个简单的答案,但我无法弄清楚正确的语法。

  $ ratelink =文本字符串... 
echo'我有以下onclick事件在PHP页面上回显:

< div>< span id =anythingonclick =updatePos('。$ ratelink。')>保存< / div>';

在我的JS页面上,我有这个功能:

 函数updatePos(ratelink)
{
alert(ratelink);
}

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



我认为以下(。 ratelink)需要使用不同的语法来传递文本,但我不知道确切的格式。 您需要在传递给JS函数时将该字符串括在引号中,以及在PHP中:

  $ ratelink ='text串...'; 
echo'< div>< span id =anythingonclick =updatePos(\''。$ ratelink.'\')> Save< / div>';


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:

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

On my JS page, I have the function:

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.

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

解决方案

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

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

这篇关于如何通过Onclick事件将PHP字符串变量传递给JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆