首先,感谢您查看我的问题,并提供任何帮助!
好吧,就像标题说我需要从我的索引页面调用一个php函数,它使用JQuery Ajax在我的数据库中添加一条新记录作为投票。此函数将返回一个整数,然后将在从中调用它的表单按钮内打印。
任何人都知道如何实现这一目标?任何指导表示赞赏!
Edit:
So if I'm using a template object I can just call the
function using ajax and it will return the output?
What would I use as the URL? index.php?
Such as...
function DoVote() {
$.ajax({
type:'POST',
url: 'index.php',
success: function(data) {
$('#voteText').html(data);
}
});
表格动作属性是我猜的?
答案 0 :(得分:3)
是的,创建一个单独的PHP文件,调用该函数并回显输出。然后使用AJAX请求加载该php文件。
因为PHP是服务器端语言而jQuery(JavaScript)是客户端,所以你不能直接用它调用PHP函数,你可以做的最多就是加载文件。但是,如果文件类似于<?php echo($object->function()); ?>
,则可以加载文件,实际上是调用函数。
我不确定(你的补充)是否正确。
在任意文件中,您有一个PHP函数:
<?php
// Called "otherfile.php"
// Function you're trying to call
function doSomething($obj)
{
$ret = $obj + 5;
return($ret);
}
?>
你有一个文件(称之为ajaxcall.php),你将使用该AJAX调用加载。
<?php
include("otherfile.php"); // Make the file available, be aware that if that file
// outputs anything (i.e. not wrapped in a function) it
// may be executed
// Grab the POST data from the AJAX request
$obj = $_POST['obj'];
echo($doSomething());
?>
答案 1 :(得分:0)
ajax请求只是强制访问一些URL,它运行位于那里的php。通过任何其他参数(甚至是GET),您可以更改被调用的函数或将这些参数传递给函数本身。