使用jQuery的Ajax调用PHP函数

使用jQuery的Ajax调用PHP函数

问题描述:

首先感谢您对检查出我的问题,和任何帮助,您可以给!

First and foremost thank you for checking out my problem, and for any help you may give!

好了,就像标题所说,我需要从我的索引页,增加了一个新的记录在我的数据库作为一票,使用JQuery的Ajax调用PHP函数。这个函数会返回有一个整数,然后将这个表单按钮,在其被从内部调用打印出来。

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. This function will return one integer, which will then be printed inside the form button in which it was called from.

任何人有我会怎样做到这一点的想法?任何指导的AP preciated!

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?

是的,创建调用该函数和回声输出一个单独的PHP文件。然后加载PHP文件与一个AJAX请求。

Yes, create a separate PHP file that calls that function and echos the output. Then load that php file with an AJAX request.

由于PHP是一种服务器端语言和jQuery(JavaScript的)是客户端,你不能的直接的调用与它的PHP函数,你最可以做的是加载一个文件。但是,如果文件中有类似< PHP的echo($对象 - >函数()); ?> 则可以加载该文件,在本质上调用该函数

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. However, if the file has something like <?php echo($object->function()); ?> you can load the file, in essence calling the function.

我不知道(你除了)是正确的。

I'm not sure that (your addition) is correct.

在任意文件,你有一个PHP函数:

In an arbitrary file you have a PHP function:

<?php
    // Called "otherfile.php"

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

        return($ret);
    }
?>

和你有一个文件(称之为ajaxcall.php),您将与AJAX调用加载。

And you have a file (call it ajaxcall.php) that you will load with that AJAX call.

<?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());
?>