2015-06-13 132 views
0

我试图定义id#的一个选项,并将其声明为变量发送到“action.php”,即连接到DB并插入值的文件。 5的ID在HTML DIV-块:发送js变量到php .ajax

<div class="rate"> 
<div id="1" class="b-1 rate-btn"></div> 
<div id="2" class="b-2 rate-btn"></div> 
<div id="3" class="b-3 rate-btn"></div> 
<div id="4" class="b-4 rate-btn"></div> 
<div id="5" class="b-5 rate-btn"></div> 
</div> 

anim.js截取点击事件,并声明变量 “therate” 为被点击 “标识”:

$('.rate-btn').click(function(){  
var therate = $(this).attr('id'); 
$('.rate-btn').removeClass('rate-btn-active'); 
for (var i = therate; i >= 0; i--) { 
$('.b-'+i).addClass('rate-btn-active'); 
$.ajax({ 
type : "POST", 
url : "action.php", 
data : therate, 
success:function(){alert(therate)} 
}); 
}; 
}); 
的上面的代码

第二部分发送“therate”var到“action.php”。但不幸的是,ID不是=(success:function(){alert(therate)}显示我在每一个选择的id#没有问题。“action.php”与“anim.js”在同一个文件夹。我也尝试过“/action.php” - 没有运气。问题是anim.js不会发送“therate”到“action.php”。我确信这是非常愚蠢和新手问题,但我不认识它=(请告诉我问题!谢谢。

+0

http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – epascarello

+0

@Rooger你的问题回答了吗? – wrxsti

回答

1

知道脚本的PHP部分将有很大的帮助这是你决定返回给客户什么样的数据通常它是这样的:

PHP

$therate = $_POST['therate']; 
$response = array(); 
if(isset($therate)){ 
    $response['status'] = 'success'; 
    $response['therate'] = $therate; 
} else { 
    $response['status'] = 'failure'; 
    $response['message'] = 'Variable therate is not set.' 
} 

echo json_encode($response); 

的jQuery

$.ajax({ 
    type : "POST", 
    url : "action.php", 
    data : {'therate': therate}, 
    success:function(data){ 
     var o = $.parseJSON(data); 
     if(o.status == 'success'){ 
      alert(o.therate); 
     } else { 
      alert(o.message); 
     } 
    } 
}); 

通知的添加来添加密钥标识符我们发送到服务器的数据。这使我们能够轻松地提取发布数据的服务器端。还要注意成功函数参数中的'数据'。这是从服务器返回的实际数据。您将在下面注意到,由于将json_encode用于传回客户端的数组,因此我们可以轻松解析为json。

我希望这有助于!如果您有任何问题,请告诉我。