代码之家  ›  专栏  ›  技术社区  ›  NickKampe

使用jquery ajax调用php函数

  •  3
  • NickKampe  · 技术社区  · 15 年前

    首先,感谢您检查我的问题,以及您可能提供的任何帮助!

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

    我猜表单动作属性已经发布了?

    2 回复  |  直到 15 年前
        1
  •  3
  •   Josh K    15 年前

    是的,创建一个单独的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);
        }
    ?>
    

    还有一个文件(称为ajax call.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());
    ?>
    
        2
  •  0
  •   Mikulas Dite    15 年前

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