简体   繁体   English

以PHP变量为参数的JavaScript函数

[英]JavaScript function with PHP variable as parameter

I've searched about escaping the parameter inside the JS function and I've tried lots of suggestions but none works. 我搜索了有关在JS函数中转义参数的信息,并且尝试了很多建议,但均无济于事。 Here is the code: 这是代码:

echo '<a class="btn btn-xs btn-danger" onclick="delete('.$fetch['bicc'].')"><span class="glyphicon glyphicon-remove"></span> Remove</a>'

I always get this error: 我总是收到此错误:

SyntaxError: identifier starts immediately after numeric literal
delete(123456789_7_ZY7)

您需要添加引号,您的param是字符串类型:

echo '<a class="btn btn-xs btn-danger" onclick="delete(\''.$fetch['bicc'].'\')"><span class="glyphicon glyphicon-remove"></span> Remove</a>'

You forgot about \\" 您忘记了\\"

onClick="delete(\"'.$fetch['bicc'].'\")"><span class="glyphicon glyphicon-remove"></span> Remove</a>

So it should be like: 所以应该像这样:

echo '<a class="btn btn-xs btn-danger" onclick="delete(\"'.$fetch['bicc'].'\")"><span class="glyphicon glyphicon-remove"></span> Remove</a>'

As a rule of thumb, if you want to use PHP variables in your JavaScript code, you need to wrap them in json_encode : 根据经验,如果要在JavaScript代码中使用PHP变量,则需要将它们包装在json_encode

echo '<a class="btn btn-xs btn-danger" onclick="delete('.json_encode($fetch['bicc']).')"><span class="glyphicon glyphicon-remove"></span> Remove</a>'

json_encode is able to take most PHP variables (strings, arrays, associative arrays) and correctly encode them as their JavaScript counterparts (eg, adding quotes for strings). json_encode能够接受大多数PHP变量(字符串,数组,关联数组),并将其正确编码为与JavaScript对应的变量(例如,为字符串添加引号)。

您应该添加引号,因为参数是字符串

echo "<a class=\"btn btn-xs btn-danger\" onclick=\"delete(\"${fetch['bicc']}\")\"><span class=\"glyphicon glyphicon-remove\"></span> Remove</a>";

$fetch['bicc'] has string type value? $ fetch ['bicc']是否具有字符串类型值?

if yes: 如是:

echo '<a class="btn btn-xs btn-danger" onclick="delete(\"'.$fetch['bicc'].'\")"><span class="glyphicon glyphicon-remove"></span> Remove</a>'
$data = str_replace('_', ' ', $fetch['bicc']);
echo '<a class="btn btn-xs btn-danger" onclick="delete('.$data.')"><span class="glyphicon glyphicon-remove"></span> Remove</a>'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM