AJAX请求工作但没有显示任何内容?

时间:2018-04-22 13:32:38

标签: javascript php ajax

我遇到了ajax请求的问题。我创建了一个问题,通过问题,当用户完成问题时,它应该调用 ajax.php 文件的请求来调出信息。请参阅下面的代码,我已经运行了 ajax.php 文件,它正在收集所有信息。但是在 tests.php 页面中,当它完成时它什么也没显示。此外,ajax $("#quiz_form,#demo1").addClass("hide")似乎没有任何显示,但没有完成下面的两个功能。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

在你的ajax.php中改变这个

echo "<div id='answer'>";
 echo " Right Answer  : <span class='highlight'>". $right_answer."</span><br>";

 echo " Wrong Answer  : <span class='highlight'>". $wrong_answer."</span><br>";

 echo " Unanswered Question  : <span class='highlight'>". $unanswered."</span><br>";
 echo "</div>";

对此:

$response = array(
    'right_answer' => $right_answer,
    'wrong_answer' => $wrong_answer,
    'unanswered' => $unanswered
);

echo json_encode($response);
exit;

阅读json_encode / json_decode

在你的ajax改变这个:

success: function(msg) {
   $("#quiz_form,#demo1").addClass("hide");
   $('#result').show();
   $('#result').append(msg);
}

用这个

success: function(data) {
   data = JSON.parse(data);
   var output = "Right Answer: "+data.right_answer + 
            "<br />Wrong Answer: " + data.wrong_answer + 
            "<br />Unanswered Question: "+ data.unanswered;
   $("#quiz_form,#demo1").addClass("hide");
   $('#result').show();
   $('#result').append(output);
}

html代码看起来应该是那样的

<div id="question_<?php echo $result['id'];?>" class='questions'></div>
<h2 id="question_<?php echo $result['id'];?>"><?php echo $result['id'].".".$result["question_name"];?></h2>
<div class='align'>
    <input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
    <label id='ans1_<?php echo $result['id'];?>' for='1'><?php echo $result['answer1'];?></label>
    <br/>
</div>
<div id="result" style="display:none;"></div>

这应该可以尝试理解代码

答案 1 :(得分:0)

使用以下内容更新您的代码,

替换您的ajax

$.ajax({
    type: "POST",
    url: "ajax.php",
    data: $('form').serialize(),
    dataType: "html",
    success: function(response){
        $("#quiz_form,#demo1").addClass("hide");
        $('#result').show();
        $('#result').append(response);
    }
});

现在删除echo中的所有ajax.php,在while循环}关闭后添加以下代码

$html = "<div id='answer'>"+
"Right Answer  : <span class='highlight'>". $right_answer."</span><br>"+
"Wrong Answer  : <span class='highlight'>". $wrong_answer."</span><br>"+
"Unanswered Question  : <span class='highlight'>". $unanswered."</span><br>"+
"</div>";
echo $html;
exit();
相关问题