首页 > 解决方案 > 在这种情况下将 javascript 变量数据传递给 MySQL 数据库

问题描述

我遵循了一个 codepen 项目来构建一个动画表单。我可以知道如何将答案存储到我的 SQL 数据库吗?答案与密钥一起存储在questions数组中,answer但我不确定如何提取它们。谢谢!

var questions = [
  {question:"What's your first name?"},
  {question:"What's your last name?"},
  {question:"What's your email?", pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/},
  {question:"Create your password", type: "password"}
]

var onComplete = function() {

    var h1 = document.createElement('h1')
    h1.appendChild(document.createTextNode('Thanks ' + questions[0].answer + ' for checking this pen out!'))
    setTimeout(function() {
      register.parentElement.appendChild(h1)
      setTimeout(function() { h1.style.opacity = 1 }, 50)
    }, 1000)

}

;(function(questions, onComplete) {

    var tTime = 100 // transition transform time from #register in ms
    var wTime = 200 // transition width time from #register in ms
    var eTime = 1000 // transition width time from inputLabel in ms

    if (questions.length == 0) return

    var position = 0

    putQuestion()

    forwardButton.addEventListener('click', validate)
    inputField.addEventListener('keyup', function(e) {
        transform(0, 0) // ie hack to redraw
        if (e.keyCode == 13) validate()
    })

    previousButton.addEventListener('click', function(e) {
        if (position === 0) return
        position -= 1
        hideCurrent(putQuestion)
    })

    function putQuestion() {
        inputLabel.innerHTML = questions[position].question
        inputField.type = questions[position].type || 'text'
        inputField.value = questions[position].answer || ''
        inputField.focus()

        progress.style.width = position * 100 / questions.length + '%'

        previousButton.className = position ? 'ion-android-arrow-back' : 'ion-person'

        showCurrent()

    }

}(questions, onComplete))

标签: javascriptphpmysqlforms

解决方案


为了使它工作,您需要为您的网站提供 jquery 支持

尝试执行以下操作:

  1. 假设您将变量存储在 JS 数组中,例如

var numbers = [45, 4, 9, 16, 25];

  1. 您可以尝试使用内置的 JS 函数来循环遍历数组,例如:

numbers.forEach(myFunction);

  1. 您定义您在第 2 点中使用的函数,使用 ajax,smth 之类的
myFunction(value){ 
// answers is used to indicate to your server side script type of operation to be performed to be use in isset(), as value is too general`

  var datastring = 'answers' + '&value=' + value;
  // in URL indicate path to your actual server side script that will put records in database

  ajax({
    type: "POST",
    url: "/app/server.php",   
    data: datastring,
    success: function (html) {
      console.log(html);
    }
  }); //End of Ajax
  
  return false;
}

推荐阅读