使用JQuery Ajax调用php函数

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

好的,就像标题所说的,我需要从索引页面调用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函数:

<?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.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...