繁体   English   中英

将 ajax 数据发布到 PHP 并返回数据

[英]post ajax data to PHP and return data

我如何将一些 ajax 数据发布到 controller function 并取回? 因为我想将一个 integer 发布到 function,然后再获得另一个 integer(我想回显该 ID 已发布的项目的总票数),并且成功。 我不知道如何将“id”发布到 controller function。 请看我的代码:

//post this integet
the_id = $(this).attr('id'); 

        $.ajax({
            type: "POST",
            data: the_id,
            url: "http://localhost/test/index.php/data/count_votes",
            success: function(){
                //the controller function count_votes returns an integer.
                //echo that with the fade in here.

                }
            });
 $.ajax({
            type: "POST",
            data: {data:the_id},
            url: "http://localhost/test/index.php/data/count_votes",
            success: function(data){
               //data will contain the vote count echoed by the controller i.e.  
                 "yourVoteCount"
              //then append the result where ever you want like
              $("span#votes_number").html(data); //data will be containing the vote count which you have echoed from the controller

                }
            });

在 controller

$data = $_POST['data'];  //$data will contain the_id
//do some processing
echo "yourVoteCount";

澄清

我觉得你很困惑

{data:the_id}

success:function(data){

为了您自己的清楚起见,这两个data都不同,您可以将其修改为

success:function(vote_count){
$(span#someId).html(vote_count);

对于 JS,请尝试

data: {id: the_id}
...
success: function(data) {
        alert('the server returned ' + data;
    }

$the_id = intval($_POST['id']);

在 PHP

那么 count_votes 是什么样的呢? 是脚本吗? Anything that you want to get back from an ajax call can be retrieved using a simple echo (of course you could use JSON or xml, but for this simple example you would just need to output something in count_votes.php like:

$id = $_POST['id'];

function getVotes($id){
    // call your database here
    $query = ("SELECT votes FROM poll WHERE ID = $id");
    $result = @mysql_query($query);
    $row = mysql_fetch_row($result);

    return $row->votes;
}
$votes = getVotes($id);
echo $votes;

这只是伪代码,但应该给你的想法。 您从 count_votes 回显的内容将是您的 ajax 调用中返回到“数据”的内容。

暂无
暂无

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

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