[英]Send js variable to a php .ajax
我试图定义一个选择的id#并将其声明为变量发送到“ action.php”,该文件连接到DB并插入值。 HTML中具有5个id的Div块:
<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拦截click事件,并将变量“ therate”声明为被单击的“ id”:
$('.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”。我敢肯定这确实是愚蠢和新手的问题,但是我不认识它=(请给我看看问题!谢谢。
了解脚本的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。
我希望这有帮助! 如果您有任何疑问,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.