javascript - 将本地存储中的数据保存到myphpadmin的数据库中

时间:2018-02-21 02:38:25

标签: javascript php mysql

hye ..我试图创建一个问答游戏,但现在我已经卡住并且已经花了好几个小时尝试将本地存储数据传输到数据库中,但数据仍然无法记录在数据库中。

这是我的js代码:

$('#start').on('click', function (e) {
    e.preventDefault();
    if(quiz.is(':animated')) {  
      return false;
    }
    $('input[type="text"]').each(function(){    
        var id = $(this).attr('id');
        var score = $(this).val();
       localStorage.setItem(id, score);
    });   
  location.href = "wheel2.html";
  });

然后,显示收集的标记:

function displayScore() {
    var score = $('<p>',{id: 'question'});   
    var numCorrect = 0;
    for (var i = 0; i < selections.length; i++) {
      if (selections[i] === questions[i].correctAnswer) {
        numCorrect+=10;
      }
    }
    score.append('You got ' + numCorrect + ' marks!! ');
 return score;
}

我也已尝试使用此代码:

var xhr;
     if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE 8 and older
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var data = "marks" + score;
         xhr.open("POST", "marks.php", true); 
         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  
         xhr.send(data);
       xhr.onreadystatechange = display_data;
      function display_data() {
       if (xhr.readyState == 4) {
          if (xhr.status == 200) {
           //alert(xhr.responseText);    
        document.getElementById("suggestion").innerHTML = xhr.responseText;
          } else {
            alert('There was a problem with the request.');
          }
         }
      }

这是我的PHP代码:

<?php
//provide your hostname, username and dbname
$host = "localhost";
$user = "root";
$password = "";
$dbname = "test1";

$conn = new mysqli($host, $user, $password, $dbname);
//$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
$sql = "INSERT INTO participant (marks)
  VALUES ('".$_POST['marks']."')";

{
echo"<script>alert('successfully registered')</script>".'<a href="wheel2.html"> back </a>';
    header('location:wheel.html?message=success');
}
?>

0 个答案:

没有答案