Ajax帖子不发送数据

时间:2013-12-28 12:35:26

标签: javascript php jquery ajax http-post

我用ajax和php构建了一个投票系统,我将数据发送到php页面,以便在db中保存数据。 我试图用ajax post和php发送数据。 我的问题是数据没有发送到页面。 我的js代码:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $.ajaxSetup({
    url: 'vote.php',
    type: 'POST',
    cache: 'false'
  });

  $('.vote').click(function(){
    var self = $(this); 
    var action = self.data('action'); 
    var parent = self.parent().parent();
    var imgid = <?=$array['id'];?>; 
    if (!parent.hasClass('.disabled')) {
      if (action == 'up') {
        parent.find('#image-like').addClass('disabled_up');
        $.ajax({data: {'imgid' : imgid, 'action' : 'up'}});
      }
      else if (action == 'down'){
        parent.find('#image-dislike').addClass('disabled_down');
        $.ajax({data: {'imgid' : imgid, 'action' : 'down'}});
      };
      parent.addClass('.disabled');
    };
  });
});
</script>

和我的HTML代码:

<a href="javascript:void(0);" id="image-like" data-action="up" class="vote"></a>
                <a href="javascript:void(0);" id="image-dislike" data-action="down" class="vote"></a>

3 个答案:

答案 0 :(得分:1)

使用post方法。这不是正确的代码,但这是一个想法,总是适合我。

$('.vote').click(function(){
//Your vars
var data='voteup';
//Your actions... ddClass/removeClass...
$.post('vote.php',data,function(data){
//On your vote.php use "if($data=='voteup') else ;"
//And show message here...
alert(data);
});
return false;
});

vote.php的例子

<?php
$data=$_POST['data'];
if($data=='voteup')
echo "You voted up!";
else echo "You voted down!";
?>

这只是一个想法(:

答案 1 :(得分:0)

您可以尝试更改此内容:

if (!parent.hasClass('.disabled')) {

到此:

if (!parent.hasClass('disabled')) {

一些注释:

From the docs

$.ajaxSetup()

  

描述:为将来的Ajax请求设置默认值。不推荐使用它。

答案 2 :(得分:0)

尝试使用.post()函数,您可以在操作完成后设置回调

jQuery.post(URL_TO_REACH, {ID_VALUE1 : 'my value' , ID_VALUE2 : 'my second value' })
                 .done(function( data_ajax ) {   // data_ajax : Your return value from your php script
                        alert( data_ajax );
                 })
              });

希望这会对你有所帮助

官方文件:http://api.jquery.com/jQuery.post/

相关问题