简单的测验 - 如何获得点击的值并将其发送到PHP

I have to write a simple quiz app. As I picked it after someone this is what I have. There are 10 questions with 3 answers each. All question are loaded at once and only one visible. After clicking the answer next question shows up etc. However as javascript is kinda magic to me I have no clue how to get all answers and send it to php to check if user chose correct. The code looks something like this:

<form action="result.php">

<div class=“quiz>
    <div class=“question”> Some question ?
        <ul>
            <li><a href=“#”>Answer A</a></li>
            <li><a href=“#”>Answer B</a></li>
            <li><a href=“#”>Answer C</a></li>
        </ul>
   </div>

[… more question here …]

<div class="question">Last question ?
        <ul>
            <li><a href=“#” onClick=“[some submit magic]">Answer A</a></li>
            <li><a href=“#” onClick=“[some submit magic]">Answer B</a></li>
            <li><a href=“#” onClick=“[some submit magic]">Answer C</a></li>
        </ul>
</div>

</div>
<input type=“hidden” name=“answers” value=“answers[]>
</form>

So basically user click on answer, next question pop up and at the end I need to populate all answer and send it to result.php where somehow I would get results within array with chosen answers like {1,3,2,1,2,3,1,2,3,1} or something like that.

There are many ways to accomplish this. Here's an easy one:

  • add a

    <input type="hidden" name="questions[]" value="" />
    

    inside each .question DIV

  • update the value of this input when one of the links are clicked:

    $('.question a').on('click', function(){
      var answer = $(this).text();
      $(this).parents('.question').find('input').val(answer);
    });
    
  • put a request method on your form, let's say POST

Then in your PHP script you'll get a numerically indexed array with the selected answer for each question, $_POST['questions'].

I do not know how your design looks like, but it may be possible to achieve this without any javascript, using hidden radio inputs and labels (I'm assuming here you're using links because of styling limitations on input fields).

Normally, you would create an HTTP request to your verification back-end. jQuery, for one, makes this quite easy. Also, I would try to generate the questions HTML, so that you're ready to generate quizzes with other sets of questions without having to re-type your html.

I'm trying to create a quizz-like app myself, currently, and would be glad to hear your feedback. A brief snipped of what I mean is on this fiddle: http://jsfiddle.net/xtofl/2SMPd/

Basically something like:

function verify(answers) {
  jQuery.ajax("http://yoursite/verify.php?answers="+answers,
     { async: true,
       complete: function(response, status){
          // e.g.
          alert(response.text);
       }
     };
  };

This request would be sent when all answers are completed. I would try to create the questions on-the-fly using javascript and the DOM, something like:

function retrieveQuestions() {
  //TODO: get them from a json-request like http://yourquizz/quizz1/questions
  return [{ text: "what if Zoo went to Blohom in a Flurk?",
           options: { a: "he frunts and vloghses", 
                      b: "the Blohom doesn't snorf anymore" }
          },
          { text: "how many this and that",
            options: { a: "1", b: "2", c: "14" }
          }
  ];
};

// retrieve and create the questions elements
var questions = retrieveQuestions();
questions.forEach(function(question, index){
  jQuery("#questions").append(createQuestionElement(question));
});

// what does a question element look like:
function createQuestionElement(question){
   var li=document.createElement("li");
   var options = [];
   Object.keys(question.options).forEach(function(key){
      var o = document.createElement("div");
      jQuery(o).on('click', function(){question.answer=jQuery(o).val();});
      li.appendChild(o);
   });
   return li;
}

Your php backend verify.php script will check the arguments and return the result in json format, e.g.:

$correct = ($answers[ $_GET["question"] ] == $_GET["answer"]);
print("{ 'correct': '$correct' }");

(provided your answers are stored in an array $answers.

Yet another solution to the problem: jsFiddle

We use event handlers, to check if an answer was clicked, then add the index of the answer to an array. When the last answer was submitted, we send the data to a php page, where you can process it using the $_POST array.

$('.question a').on('click', function (e) {
    e.preventDefault();
    var self = $(this);
    var ans = self.parent().index() + 1;
    answers.push(ans);
    var hasNext = nextQuestion();
    if (!hasNext) {
        $.ajax({
            type: "POST",
            url: "/echo/json/",
            data: {
                "answers": answers
            }
        }).done(function (response) {
            response = 'Stuff you output with PHP';
            $('body').append('<p> Result: ' + response + '</p>');
        });
    }
});