我有一个 ajax 函数,应该将一些数据发布到另一个页面,但由于某种原因它似乎没有发布。
我不知道为什么这不起作用,我在过去的一个小时里一直在研究它。
Ajax函数
$(document).ready(function()
{
$('.rate').click(function(){
var ratingId = $('#ratingID').val();
var clickBtnValue = $(this).val();
var ajaxurl = 'ProcessRating.php',
data = {'action': clickBtnValue, 'ratingID': ratingId};
$.post(ajaxurl, data, function (response)
{
alert("action performed successfully");
});
});
});
在主页上
<?php
session_start();
echo $_SESSION["messege"];
?>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
</script>
<script>
//The Ajax function is here
</script>
</head>
<body>
<form>
<input type="hidden" class="rate" id="ratingID" name="ratingID" value =
"<?php echo $article->getId()?>" />
<input type="submit" class="rate" name="1" value="1" />
<input type="submit" class="rate" name="2" value="2" />
<input type="submit" class="rate" name="3" value="3" />
<input type="submit" class="rate" name="4" value="4" />
<input type="submit" class="rate" name="5" value="5" />
</form>
</body>
在 ProcessRating.php 页面上
<?php
session_start();
$_SESSION["messege"] = "got This far";
if (isset($_POST['action']))
{
$id = $_POST['ratingID'];
switch ($_POST['action']) {
case '1':
updateRating($db, $id, "oneStar");
break;
case '2':
updateRating($db, $id, "twoStar");
break;
case '3':
updateRating($db, $id, "threeStar");
break;
case '4':
updateRating($db, $id, "fourStar");
break;
case '5':
updateRating($db, $id, "fiveStar");
break;
}
$rating = getAvgRating($db, $id);
updateArticleRating($db, $id, $rating);
}
最佳答案
1.由于所有按钮类型都是submit
它们位于 <form></form>
内.所以你必须使用preventDefault()
以防止正常的表单发布。
如下所示:-
$(document).ready(function(){
$('.rate').click(function(e){
e.preventDefault();
var ratingId = $('#ratingID').val();
var clickBtnValue = $(this).val();
var ajaxurl = 'ProcessRating.php',
data = {'action': clickBtnValue, 'ratingID': ratingId};
$.post(ajaxurl, data, function (response){
alert("action performed successfully");
});
});
});
2.确保ajaxurl
那里是正确的。(检查控制台是否正确,如果 URL 中有错误,您肯定会在控制台中看到)
重要说明:-
检查您的浏览器控制台是否有任何错误?如果是,请告诉我们。
关于javascript - ajax 未发布到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43709638/