如何更改按钮的颜色并加载问题,如果在不加载整个页面的情况下按下了另一个按钮?

时间:2019-04-06 15:29:08

标签: php jquery ajax

我正在建立一个在线考试网站,用户可以登录该网站进行考试。
我在问题旁边有一个面板,如果单击这些按钮,将给出不同的问题编号按钮,该问题将在不加载整个页面的情况下从数据库中出现。我遇到了该怎么做的问题?

HTML代码-

**<div>
<button type="button" class="btn btn-info custom" style="margin-right:16px">13</button>
<button type="button" class="btn btn-info custom" style="margin-right:16px">14</button>
<button type="button" class="btn btn-info custom" style="margin-right:16px">15</button>
</div>**

如何编写jquery ajax和php代码?

1 个答案:

答案 0 :(得分:0)

我创建了php文件(test.php),并执行了ajax调用并根据问题ID获取问题的客户端。代码在

下面

PHP文件代码(test.php)

<?php 
//it's used because the server is local, without it throws console error
//and doesn't allow to proceed with the operation.
//No need for remote servers
header('Access-Control-Allow-Origin: *');

if(isset($_GET['questionId'])){
    $qId = $_GET['questionId'];

    if($qId == 12){
      echo "Question 1";
    }

    if($qId == 13){
      echo "Question 2";
    }
}

?>

$(".btn > button").click(function(){
    //get button text and send it to server file to give you back response accordingly
    var qId = $(this).text();
    alert("Question ID:"+qId);
    
    /*$.ajax({
       method:'get',
       url:'http://localhost/test.php'
       //send question ID to server file
       data:{questionId: qId }
    }).done(function( data ) {
       console.log( "Sample of data:"+data);
    }).fail(function( jqXHR, textStatus ) {
       alert( "Request failed: " + textStatus );
    });*/
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn">
<button type="button" class="btn btn-info custom" style="margin-right:16px">13</button>
<button type="button" class="btn btn-info custom" style="margin-right:16px">14</button>
<button type="button" class="btn btn-info custom" style="margin-right:16px">15</button>
</div>