在javascript代码中使用php函数

时间:2013-12-01 20:54:52

标签: javascript php

我想从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代码。

3 个答案:

答案 0 :(得分:2)

你做不到。 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 injection

的影响

答案 1 :(得分:1)

你不能在Javascript中运行php代码,但你可以通过JS / Ajax发送它。为了良好的实践,拆分你的php和JS,例如创建一个带有ID的页面并删除它的行(我猜你使用REST)并通过JS调用它。

更清洁,更有效,更安全

答案 2 :(得分:1)

根据你的问题,我建议你试试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如果您发现任何其他问题,请告诉我

这是google 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
?>

这应该为你做。