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

bil*_*lla 10 php jquery post codeigniter

如何将一些ajax数据发布到控制器功能并将其恢复?因为我想将一个整数发布到函数中,并获得另一个整数(对于发布ID的项目的总投票数),并且在成功时我想要回显该投票计数.我不知道如何将"id"发布到控制器功能.请看我的代码:

//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.

                }
            });
Run Code Online (Sandbox Code Playgroud)

Raf*_*fay 18

 $.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

                }
            });
Run Code Online (Sandbox Code Playgroud)

在控制器中

$data = $_POST['data'];  //$data will contain the_id
//do some processing
echo "yourVoteCount";
Run Code Online (Sandbox Code Playgroud)

澄清

我觉得你很困惑

{data:the_id}
Run Code Online (Sandbox Code Playgroud)

success:function(data){
Run Code Online (Sandbox Code Playgroud)

两者都有data所不同,为了您自己的清晰度,您可以将其修改为

success:function(vote_count){
$(span#someId).html(vote_count);
Run Code Online (Sandbox Code Playgroud)


Mar*_*c B 5

对于JS,尝试

data: {id: the_id}
...
success: function(data) {
        alert('the server returned ' + data;
    }
Run Code Online (Sandbox Code Playgroud)

$the_id = intval($_POST['id']);
Run Code Online (Sandbox Code Playgroud)

在 PHP 中


ser*_*orm 5

那么 count_votes 是什么样的呢?它是一个脚本吗?您想要从 ajax 调用返回的任何内容都可以使用简单的 echo 来检索(当然您可以使用 JSON 或 xml,但对于这个简单的示例,您只需要在 count_votes.php 中输出一些内容,例如:

$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;
Run Code Online (Sandbox Code Playgroud)

这只是伪代码,但应该可以让您了解。您从 count_votes 中回显的内容将是您的 ajax 调用中返回到“数据”的内容。