表单与jquery结合PHP发送结果*更新完整的代码*

form with jquery combined with php to send result *updated with full code*

本文关键字:更新 代码 结果 jquery 结合 PHP 表单      更新时间:2023-09-26

更新完整代码如下。还有调整问题

会发生什么?在回答完所有问题后,endQuiz会触发并给用户一个分数。还会出现一个表单,我希望用户填写并将其发送到特定的电子邮件帐户。但是当我填写表格并按"发送"时,当测试在我公司的服务器上运行时,我得到了一个405错误。当我在本地运行它时,什么也没有发生。

index . html:

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script language="javascript" type="text/javascript">
     var quiztitle = "quiz title";
     var quiz = [
            {
                "question" : "q1",
                "image" : "http://www.saferinternet.org/image/image_gallery?uuid=b243b830-e3fd-49b9-ad2c-43b2ff073db8&groupId=10137&t=1359909134797",
                "choices" : [
                                        "a1",
                                        "a2",
                                        "a3",
                                        "a4"
                                    ],
                "correct" : "a2",
                "explanation" : "good job"
            },
            {
                "question" : "q2",
                "image" : "http://www.saferinternet.org/image/image_gallery?uuid=b243b830-e3fd-49b9-ad2c-43b2ff073db8&groupId=10137&t=1359909134797",
                "choices" : [
                                        "a1",
                                        "a2"
                                    ],
                "correct" : "a2",
                "explanation" : "good job"
            },
            {
                "question" : "q3",
                "image" : "http://www.saferinternet.org/image/image_gallery?uuid=b243b830-e3fd-49b9-ad2c-43b2ff073db8&groupId=10137&t=1359909134797",
                "choices" : [
                                        "a1",
                                        "a2",
                                        "a3",
                                        "a4"
                                    ],
                "correct" : "a3",
                "explanation" : "good job"
            }
        ];
     var currentquestion = 0,
         score = 0,
         submt = true,
         picked;
         $(document).ready(function(){
           $("#submitbutton").hide();
          function htmlEncode(value) {
             return $(document.createElement('div')).text(value).html();
         }
           function addChoices(choices) {
             if (typeof choices !== "undefined" && $.type(choices) == "array") {
                 $('#choice-block').empty();
                 for (var i = 0; i < choices.length; i++) {
                     $(document.createElement('li')).addClass('choice choice-box').attr('data-index', i).text(choices[i]).appendTo('#choice-block');
                 }
             }
         }
          function nextQuestion() {
             submt = true;
            //alert("nQ");
             $('#explanation').empty();
             $('#question').text(quiz[currentquestion]['question']);
             $('#pager').text('Q ' + Number(currentquestion + 1) + ' of ' + quiz.length);
             if (quiz[currentquestion].hasOwnProperty('image') && quiz[currentquestion]['image'] != "") {
                 if ($('#question-image').length == 0) {
                     $(document.createElement('img')).addClass('question-image').attr('id', 'question-image').attr('src', quiz[currentquestion]['image']).attr('alt', htmlEncode(quiz[currentquestion]['question'])).insertAfter('#question');
                 } else {
                     $('#question-image').attr('src', quiz[currentquestion]['image']).attr('alt', htmlEncode(quiz[currentquestion]['question']));
                 }
             } else {
                 $('#question-image').remove();
             }
             addChoices(quiz[currentquestion]['choices']);
             setupButtons();
         }
           function processQuestion(choice) {
             //alert(choice);
             currentquestion++;
              //alert(currentquestion);
             $("#submitbutton").hide();
                 if (currentquestion == quiz.length) {
                     endQuiz();
                 } else {
                     nextQuestion();
                 }
         }
          function setupButtons() {
             $('.choice').on('mouseover', function () {
                 $(this).css({
                     'background-color': '#e1e1e1'
                 });
             });
             $('.choice').on('mouseout', function () {
                 $(this).css({
                     'background-color': '#fff'
                 });
             })
             $('.choice').on('click', function () {
                 //alert("");
                 choice = $(this).attr('data-index');
                 $('.choice').remove();
                 if (quiz[currentquestion]['choices'][choice] == quiz[currentquestion]['correct']) {
                 $('.choice').eq(choice).css({
                     'background-color': '#50D943'
                 });
                 $('#explanation').html('<p style="background-color:green;">Score! <strong>' + quiz[currentquestion]['correct'] + 'Thats the right answer!</p>' + htmlEncode(quiz[currentquestion]['explanation']));
                 score++;
             } else {
                 $('.choice').eq(choice).css({
                     'background-color': '#D92623'
                 });
                 $('#explanation').html('<p style="background-color:red;">Sorry!' +quiz[currentquestion]['choices'][choice] + 'Thats the wrong answer!</p>' + htmlEncode(quiz[currentquestion]['explanation']));
             }
                    $("#submitbutton").show();
                 if (submt) {
                    ////alert("submit");
                     submt = false;
                     $('#submitbutton').css({
                         'color': '#000'
                     });
                     $("#submitbutton").click(function(){
                    ////alert("click");
                          $('.choice').off('click');
                         $(this).off('click');
                         processQuestion(choice);
                     });
                 }
             })
         }
          function endQuiz() {
         $('#explanation').remove();
         $('#question').empty();
         $('#choice-block').remove();
         $('#submitbutton').remove();
         $('#question-image').remove();
        if (score > 2) {
            $('#question').text("best " + score + " of " + quiz.length + " correct.");
        }
        if (score > 1 && score < 3) {
            $('#question').text("ok " + score + " of " + quiz.length + " correct.");
        }
        if (score < 2) {
            $('#question').text("poor " + score + " of " + quiz.length + " correct.");
        }
        if (score < 1) {
            $('#question').text("worst " + score + " of " + quiz.length + " correct.");
        }
         $(document.createElement('h2')).css({
             'text-align': 'center',
             'font-size': '4em'
         }).text(Math.round(score / quiz.length * 100) + '%').insertAfter('#question');
        $(document.createElement('form')).addClass('form').attr({method:'post', action:'mail.php', id: 'form'}).html('Please fill out the form').appendTo('#frame');
        $("<input type='text' name='yourname' id='yourname' placeholder='Your name' />").appendTo('.form');
        $("<input type='text' name='municipality' id='municipality' placeholder='Your municipality' />").appendTo('.form');
        $("<input type='text' name='email' id='email' placeholder='Your e-mail' />").appendTo('.form');
        $(document.createElement('header')).addClass('formheader').text('Give your municipality a point!').appendTo('.form');
        $("<input type='radio' name='points' id='points1' title='1' value='1' />").appendTo(".form");
        $("<label for='points1' />").text('1').appendTo('.form');
        $("<input type='radio' name='points' id='points2' title='2' value='2' />").appendTo('.form');
        $("<label for='points2' />").text('2').appendTo('.form');
        $("<input type='radio' name='points' id='points3' title='3' value='3' />").appendTo('.form');
        $("<label for='points3' />").text('3').appendTo('.form');
        $("<input type='radio' name='points' id='points4' title='4' value='4' />").appendTo('.form');
        $("<label for='points4' />").text('4').appendTo('.form');
        $("<input type='radio' name='points' id='points5' title='5' value='5' />").appendTo('.form');
        $("<label for='points5' />").text('5').appendTo('.form');
        $(document.createElement('textarea')).addClass('mail_text').attr('id', 'text_mail').text('Please send us your story!').appendTo('.form');
        $("<input type='submit' id='sendForm' class='sendForm' name='sendForm' value='Press to send!'/>").appendTo('.form');
      }
    function sendForm() {
$('#form').submit(function(event){
    $('#sendForm').attr('value','Your answer was sent!');
    setTimeout(function(){
        $('#sendForm').attr('value','Sending...');
    }, 2000);
    var stuff = $('#form').serialize();
    jQuery.ajax({
        type: 'POST',
        url: 'mail.php', 
        data: stuff,
        dataType: "json"
    });
    //Prevents form submission
    return false;        
});
}
          function init() {
             //add title
             if (typeof quiztitle !== "undefined" && $.type(quiztitle) === "string") {
                 $(document.createElement('h1')).text(quiztitle).appendTo('#frame');
             } else {
                 $(document.createElement('h1')).text("Quiz").appendTo('#frame');
             }
             //add pager and questions
             if (typeof quiz !== "undefined" && $.type(quiz) === "array") {
                 //add pager
                 $(document.createElement('p')).addClass('pager').attr('id', 'pager').text('Q 1 of ' + quiz.length).appendTo('#frame');
                 //add first question
                 $(document.createElement('h2')).addClass('question').attr('id', 'question').text(quiz[0]['question']).appendTo('#frame');
                 //add image if present
                 if (quiz[0].hasOwnProperty('image') && quiz[0]['image'] != "") {
                     $(document.createElement('img')).addClass('question-image').attr('id', 'question-image').attr('src', quiz[0]['image']).attr('alt', htmlEncode(quiz[0]['question'])).appendTo('#frame');
                 }
                 $(document.createElement('p')).addClass('explanation').attr('id', 'explanation').html('&nbsp;').appendTo('#frame');
                 //questions holder
                 $(document.createElement('ul')).attr('id', 'choice-block').appendTo('#frame');
                 //add choices
                 addChoices(quiz[0]['choices']);
                 //add submit button
                 $(document.createElement('div')).addClass('choice-box').attr('id', 'submitbutton').text('Nästa fråga').css({
                     'font-weight': 700,
                     'color': '#222',
                     'padding': '30px 0',
                  }).appendTo('#frame');

               $("#submitbutton").hide();
                 setupButtons();
             }
         }
         init();
     }); 
    </script>
    </head>
    <body>
     <div id = "frame" role = "content"></div>
    </body>
    </html>

mail.php

<?php parse_str($_POST['stuff']);  mail("test@mymail.org", "Title", "$yourname, $email, $points, $text_mail");  ?>

你的jQuery选择器似乎不匹配。

你正在寻找。sendForm类的提交处理程序,但你的表单属性是ID为#sendForm与类。submitform

然后你再做一次,你的表单被CLASSED为.form从addClass()方法创建,但然后你试图发送#表单Id的数据,这并不存在。

$(document.createElement('form')).addClass('form')

 stuff = $('#form').serialize();

它解释了为什么没有发生任何事情,因为您没有将元素链接到您期望进入的内容。