我是jquery的初学者“实际上是我的第一个代码”。我正在研究星级评分系统,jquery部分工作得很好,它返回了rate的值。但是当涉及到PHP代码时,它确实做到了!我想从(index.php)传递(rate变量)到(rate.php)文件,以便将其插入(速率)表。请帮帮我
的index.php:
<!DOCTYPE html class="ng-scope" ng-app="">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/ca-pub-2074772727795809.js" type="text/javascript" async=""></script>
<script src="js/analytics.js" async=""></script>
</head>
<body>
<h1>please Rate:</h1>
<script>
$(function(){
$(".stars").on("click", function(){
var rate = $(this).val();
alert(rate);
});
});
</script>
<fieldset id='starset' class="rating" name="star">
<input class="stars" type="radio" id="star5" name="rating" value="5" />
<label class = "full" for="star5" title="Awesome - 5 stars"></label>
<input class="stars" type="radio" id="star4" name="rating" value="4" />
<label class = "full" for="star4" title="Pretty good - 4 stars"></label>
<input class="stars" type="radio" id="star3" name="rating" value="3" />
<label class = "full" for="star3" title="Meh - 3 stars"></label>
<input class="stars" type="radio" id="star2" name="rating" value="2" />
<label class = "full" for="star2" title="Kinda bad - 2 stars"></label>
<input class="stars" type="radio" id="star1" name="rating" value="1" />
<label class = "full" for="star1" title="Sucks big time - 1 star"></label>
</fieldset>
</body>
rate.php:
<?php
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("HWP",$connect);
$rate=$_POST['val']
if (isset($rate) && !empty($rate))
{
$query1 = mysql_query("select rate_id FROM rate WHERE Rate_cust_id= 1");
$f1 = mysql_num_rows($query1);
if (mysql_num_rows($query1) > 0)
{
echo $f1['rate_id'];
}
else
{
$query2= mysql_query("insert into rate ( rate_value, rate_cust_id , rate_hw_id) VALUES ($rate, 4 , 2); ");
if ($query2) {
echo "0";
}
}
}
?>
答案 0 :(得分:1)
您需要AJAX
与JQuery
一起使用才能发送您的价值:
<script>
$(function() {
$(".stars").on("click", function() {
var rate = $(this).val();
$.post("rate.php", {
val: rate
},
function(data, status) {
// here you can get the data sent from PHP with data variable & the status of the request with status variable
//alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
此外,请注意使用PDO
或mysqli
来处理您的请求。 mysql
已被弃用,可能对SQL injections
容易受到攻击
如果您仍想使用mysql
并且不使用mysqli
或PDO
,则可以使用此mysql函数从用户转义字符串以阻止SQL injection
:< / p>
$secure = mysql_real_escape_string($_POST['val']);
最后,请注意代码中未定义$cus_id
变量,这会导致错误。
请记住:从不信任用户
来源(如果需要):http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
PS: Ajax是一种向页面发送
$_GET
或$_POST
请求的技术
您可以将$.get
用于获取请求,将$.post
用于您的帖子请求
答案 1 :(得分:0)
<script>
$(function(){
$(".stars").on("click", function(){
var rate = $(this).val();
$.post('rate.php', {val: rate}, function(data){...})
});
});
</script>
还要注意注射风险,逃避并验证来自用户的一切,绝对是一切。