简体   繁体   English

在PHP中回荡Javascript?

[英]Echoing Javascript within PHP?

I am trying to generate a delete button in my PHP which will delete a row from the database on click. 我试图在我的PHP中生成一个删除按钮,该按钮将在单击时从数据库中删除一行。 I would also like to throw a confirmation message via Javascript within this link but can't seem to figure out how to structure the code. 我也想在此链接中通过Javascript发出一条确认消息,但似乎无法弄清楚如何构造代码。

Here is what I have so far: 这是我到目前为止的内容:

echo "<td class='delete'><a href='?page=db&amp;delete=".$row->id."' onclick='return confirm('are you sure?')'>Delete</a></td>";

I am guessing the reason this isn't working is due to the double/single quotes. 我猜这不起作用的原因是由于双引号/单引号。 Can anyone tell me how I would format this properly? 谁能告诉我如何正确格式化? Thank you. 谢谢。

You can either use: 您可以使用:

  • Double quotes (which would have to be escaped for PHP) 双引号(PHP必须转义)
  • Character references for single quotes 单引号的字符引用
  • Character references for double quotes 双引号的字符引用

Such 这样

onclick='return confirm(\"are you sure?\")'>

That said, I'd rewrite this to not have JavaScript nested inside HTML inside PHP inside HTML since that just becomes horrible to try to track. 就是说,我会重写此代码,以使JavaScript不会嵌套在HTML内的HTML内,而在HTML内的HTML内,因为这样很难追踪。

<td class='delete'>
   <a href="?page=db&amp;delete=<?php echo $row->id; ?>" 
      class="delete">Delete</a>
</td>

and then, using jQuery because it is convenient for this kind of event binding: 然后使用jQuery,因为这种事件绑定很方便:

<script>
    jQuery("a.delete").on('click', function (evt) {
        if (! confirm('are you sure?')) {
            evt.preventDefault();
        }
    });
</script>

Since you shouldn't do unsafe operations using a GET request, I'd even go a step further and use a form. 由于您不应使用GET请求执行不安全的操作,因此,我什至更进一步,并使用表单。

<td class='delete'>
   <form method="post">
       <input type="hidden" name="page" value="db">
       <button name="delete" value="<?php echo $row->id; ?>">
           Delete
       </button>
   </form>
</td>

<script>
    jQuery("td.delete > form").on('submit', function (evt) {
        if (! confirm('are you sure?')) {
            evt.preventDefault();
        }
    });
</script>

你可以试试这个

echo '<td class="delete"><a href="?page=db&amp;delete='.$row->id.'" onclick="return confirm(\'are you sure?\')">Delete</a> </td>';

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

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