简体   繁体   English

使用JQuery Ajax调用php函数

[英]Using JQuery Ajax to call a php function

First and foremost thank you for checking out my problem, and for any help you may give! 首先,感谢您查看我的问题,以及您可能给予的任何帮助!

Okay, so like the title says I'm in need of calling a php function from my index page, which adds a new record in my database as a vote, using JQuery Ajax. 好吧,就像标题所说我需要从我的索引页面调用一个php函数,它使用JQuery Ajax在我的数据库中添加一条新记录作为投票。 This function will return one integer, which will then be printed inside the form button in which it was called from. 此函数将返回一个整数,然后将其打印在调用它的表单按钮内。

Anyone have an idea on how I would accomplish this? 任何人都知道如何实现这一目标? Any guidance is appreciated! 任何指导表示赞赏!

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);
 }
});

And the form action attribute is posted I'm guessing? 表格动作属性是我猜的?

Yes, create a separate PHP file that calls that function and echos the output. 是的,创建一个单独的PHP文件来调用该函数并回显输出。 Then load that php file with an AJAX request. 然后使用AJAX请求加载该php文件。

Because PHP is a server side language and jQuery (JavaScript) is Client side you can't directly call a PHP function with it, the most you can do is load a file. 因为PHP是服务器端语言而jQuery(JavaScript)是客户端,所以你不能用它直接调用PHP函数,你可以做的最多就是加载文件。 However, if the file has something like <?php echo($object->function()); ?> 但是,如果文件类似于<?php echo($object->function()); ?> <?php echo($object->function()); ?> you can load the file, in essence calling the function. <?php echo($object->function()); ?>可以加载该文件,在本质上调用该函数。

I'm not sure that (your addition) is correct. 我不确定(你的补充)是否正确。

In an arbitrary file you have a PHP function: 在任意文件中,您有一个PHP函数:

<?php
    // Called "otherfile.php"

    // Function you're trying to call
    function doSomething($obj)
    {
        $ret = $obj + 5;

        return($ret);
    }
?>

And you have a file (call it ajaxcall.php) that you will load with that AJAX call. 你有一个文件(称之为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());
?>

The ajax request simply forces some URL to be access, which runs the php located there. ajax请求只是强制访问一些URL,它运行位于那里的php。 And by any additional parameters (even GET) you may either change the function being called or pass these to the function itself. 通过任何其他参数(甚至GET),您可以更改被调用的函数或将这些参数传递给函数本身。

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

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