这是回复变量$correct
的php页面。其初始值为0
。它的值随着值的增加而变化,但是当我使用jquery ajax方法将其回显到其他页面后加载此值时,它仅返回0
而不是增量值。
<?php
$i=1;
while($i<=10) {
$answer="answer_".$i;
${"answer_$i"}=$_POST[$answer];
$i++;
}
$correct=0;
if($answer_1=="a")
$correct=$correct+10;
else {
if($answer_1=="b" || $answer_1=="c" || $answer_1=="d")
$correct=$correct-10;
}
if($answer_2=="a")
$correct=$correct+10;
else {
if($answer_2=="b" || $answer_2=="c" || $answer_2=="d")
$correct=$correct-10;
}
if($answer_3=="a")
$correct=$correct+10;
else {
if($answer_3=="b" || $answer_3=="c" || $answer_3=="d")
$correct=$correct-10;
}
if($answer_4=="a")
$correct=$correct+10;
else
{ if($answer_4=="b" || $answer_4=="c" || $answer_4=="d")
$correct=$correct-10;
}
if($answer_5=="a")
$correct=$correct+10;
else
{ if($answer_5=="b" || $answer_5=="c" || $answer_5=="d")
$correct=$correct-10;
}
if($answer_6=="a")
$correct=$correct+10;
else
{ if($answer_6=="b" || $answer_6=="c" || $answer_6=="d")
$correct=$correct-10;
}
if($answer_7=="a")
$correct=$correct+10;
else
{ if($answer_7=="b" || $answer_7=="c" || $answer_7=="d")
$correct=$correct-10;
}
if($answer_8=="a")
$correct=$correct+10;
else {
if($answer_8=="b" || $answer_8=="c" || $answer_8=="d")
$correct=$correct-10;
}
if($answer_9=="a")
$correct=$correct+10;
else
{
if($answer_9=="b" || $answer_9=="c" || $answer_9=="d")
$correct=$correct-10;
}
if($answer_10=="a")
$correct=$correct+10;
else
{
if($answer_10=="b" || $answer_10=="c" || $answer_10=="d")
$correct=$correct-10;
}
echo "$correct";
?>
这是访问此变量$correct
的其他页面上的脚本,但它总是导致0
,尽管变量值在php页面上发生变化?我怎么能纠正这个?
<script>
$(function(){
$('form').submit(function(event){
event.preventDefault();
$.ajax({
url:"results.php",
type:"POST",
success:function(result){
console.log(result);
$('#results').html("<p>"+result+"</p>");
}
});
});
});
</script>
答案 0 :(得分:0)
您没有将任何答案从AJAX传递给PHP 因此,您的PHP中没有任何条件得到满足 因此它返回0.
要使用post请求传递数据,请参阅ajax文档(http://api.jquery.com/jQuery.ajax/)。您需要查看data
属性。
你会想要这样的东西:
$.ajax({
url:"results.php",
type:"POST",
data: {
answer_1: 'blue' // what colour is the sky?
},
success:function(result){
console.log(result);
$('#results').html("<p>"+result+"</p>");
}
});
然后你的PHP需要收集数据,但我想你已经有了这个设置:
$answer1 = $_POST['answer1'];
<小时/> 的更新强> 包含来自用户评论的示例信息。
<input type="radio" name="answer_1" value="a" id="question_1_answer_a"/>
<label for="question_1_answer_a">anirudh</label>
<input type="radio" name="answer_1" value="b" id="question_1_answer_b"/>
<label for="question_1_answer_b">anirudh</label>
所以你想要这样的东西:
data: {
answer_1: $('input[name="answer_1"]').val(), // from HTML example
answer_2: $('input[name="answer_2"]').val(),
answer_3: $('input[name="answer_3"]').val()
// etc
},
如果您不打算使用jQuery修改任何表单数据,您可以随时对其进行序列化并将其发布:http://api.jquery.com/serialize/