我想从javascript代码中运行一个php函数,更具体地说,我得到了一个从数据库中删除记录的按钮。执行此操作的函数名为
delete_post($id)
以下是我尝试过的:
<input type="submit" name="delete" value="delete"
onClick="if(confirm('Are you sure?')) {<?php delete_post($row['id']);?>}">
当我单击该按钮时,没有警报框。有趣的是,如果我不在php代码中调用函数,而我做了其他事情,比如echo,警报会弹出,但php代码不会执行。
那么,我该怎么做呢?如何在javascript onClick代码中运行php代码。
你不能。PHP应该在页面加载之前运行,因此将其命名为Pre Hypertext Protocol。如果您想在通过JavaScript加载页面后运行PHP,最好的方法是链接到运行PHP的新页面,然后返回用户。
file1.php:
...
<input type="submit" name="delete" value="delete" onClick="if(confirm('Are you sure?')) document.location.href='file2.php';">
...
file2.php:
<!doctype html>
<html>
<head>
<?php
delete_post($row['id']);
?>
<meta http-equiv="refresh" content="0; url=file1.php" />
</head>
<body>
<p>You will be redirected soon; please wait. If you are not automatically redirected, <a href="file1.php">click here</a>.</p>
</body>
</html>
假设你有多个ID,你可以把它们都放在一个重定向页面上:
if(confirm('Are you sure?')) document.location='file2.php?id=2'; // file1.php
delete_post($row[$_GET["id"]]); // file2.php
但是不要将PHP代码直接放入查询字符串中,否则您的网站可能会受到PHP注入的影响
您不能在Javascript中运行php代码,但您可以通过JS/Ajax进行INVOKE。为了更好地分离php和JS,例如创建一个带有ID并删除其行的页面(我猜您使用的是REST),然后通过JS调用它。
更清洁、有效、更安全的
根据您的问题,我建议您尝试一下jquery。
链接到Jquery在您的页面的标题部分,
这是你的js函数
function deleteRow(id)
{
var url='path/to/page.php';
$("#loading_text").html('Performing Action Please Wait...');
$.POST(url,{ row_id: id } ,function(data){ $("#loading_text").html(data) });
}
这应该为你做。
由于它是一个删除,我使用$.post
如果你发现还有任何问题,请告诉我
这里有一个链接到由谷歌CDN托管的jQuery//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js
这就是你的表单应该看起来像的样子
<form>
<label for="Number"></label>
<input type="text" name="some_name" id="some_id" value="foo bar">
<input type="submit" name="delete" value="delete"
onClick="javascript: deleteRow(the_id_of_the_row);">
</form>
<br>
<div id="loader_text"></div>
现在,你的php页面删除可能看起来像这个
<?php
$row_id = some_sanitisation_function($_POST['row_id']) //so as to clean and check user input
delete_post($row_id);
echo "Row deleted Successfully"; //success or failure message
?>
这应该为你做。