有没有一种方法可以提交表单而无需仅使用PHP和JavaScript刷新页面?

时间:2019-05-19 15:00:30

标签: php

我在大学里有一个项目,并且我不想在提交表单后刷新页面。

问题在于,对于该项目,我只能使用基本的编程语言,因此,我不能使用jQuery(我使用post方法找到了解决方案)或任何类型的库或框架。还有其他方法吗?

如果没有其他库/框架就无法做到这一点,那么使用PHP获取表单信息的最佳方法是什么?表单应该具有GET或POST方法吗?我在网上看到了许多不同的类型,我想确定哪种类型最合适(例如登录,注册表单,例如我在项目中确实有的表单)。

2 个答案:

答案 0 :(得分:0)

您可以使用纯JS和PHP,这是一个简单的示例。您可以使用事件侦听器和 XMLHttpRequest 对象发出请求。我建议使用POST请求。

POST和GET有什么区别?

GET和POST方法都用于通过HTTP协议将数据从客户端传输到服务器,但是这两种方法之间的主要区别在于GET带有附加在URL字符串中的请求参数,而POST带有消息正文中的请求参数,这使得它使用HTTP协议将数据从客户端传输到服务器的更安全的方法。通常,当您处理诸如 pass email 之类的数据时,必须使用POST以避免安全问题

var myForm = document.getElementById('my_form');

myForm.addEventListener('submit', (e) => {
  e.preventDefault(); // To avoid the page refresh when you click on submit button
})

function login() {
  let userEmail = document.getElementById("email_field").value
  let userPass = document.getElementById("password_field").value
  console.log(`Email: ${userEmail} - Pass: ${userPass}`); // Will print your data
  
  let http = new XMLHttpRequest();
  let url = 'get_data.php'; // Your PHP controller
  let params = `email=${userEmail}&pass=${userPass}`;
  http.open('POST', url, true);

  // Send the proper header information along with the request
  http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

  http.onreadystatechange = function() { // Call a function when the state changes.
      if (http.readyState == 4 && http.status == 200) {
          alert(http.responseText);
      } else {
          console.log('Unable to make the request');
      }
  }
  http.send(params);
}
 <form id="my_form">
    <div>
      <input type="email" id="email_field" placeholder="email">
    </div>
    <div>
      <input type="password" id="password_field" placeholder="password">
    </div>
    <button onclick="login()">login</button>
  </form>

答案 1 :(得分:0)

您尝试过this吗?由于您不能使用框架或库,因此只需使用javascript的XMLHttpRequest对象。不要忘记制作一个PHP脚本来处理该请求。

有关HTTP方法的选择,如果要符合RESTful API标准,可以参考this文档。