繁体   English   中英

使用JQuery Ajax调用php函数

[英]Using JQuery Ajax to call a php function

首先,感谢您查看我的问题,以及您可能给予的任何帮助!

好吧,就像标题所说我需要从我的索引页面调用一个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);
 }
});

表格动作属性是我猜的?

是的,创建一个单独的PHP文件来调用该函数并回显输出。 然后使用AJAX请求加载该php文件。

因为PHP是服务器端语言而jQuery(JavaScript)是客户端,所以你不能用它直接调用PHP函数,你可以做的最多就是加载文件。 但是,如果文件类似于<?php echo($object->function()); ?> <?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());
?>

ajax请求只是强制访问一些URL,它运行位于那里的php。 通过任何其他参数(甚至GET),您可以更改被调用的函数或将这些参数传递给函数本身。

暂无
暂无

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

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