Как изменить цвет кнопки и загрузить вопрос, если нажата другая кнопка без загрузки всей страницы? - PullRequest
0 голосов
/ 06 апреля 2019

Я делаю сайт для онлайн-экзаменов, где пользователи могут войти, чтобы сдать экзамены.
У меня есть панель рядом с вопросом, где дана кнопка с другим номером вопроса, если вы нажмете на кнопки, вопрос появится из базы данных без загрузки всей страницы. Я сталкиваюсь с проблемой, как мне это сделать?

КОД 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 голосов
/ 06 апреля 2019

Я создал 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...