首页 > 解决方案 > PHP 表单提交是否会导致整个文件刷新?

问题描述

当用户点击提交时,使用<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">会导致整个页面刷新吗?还是只是 PHP 部分?

标签: phphtmlajaxxss

解决方案


页面通常会在提交表单后重新加载,以显示提交表单后收到的响应。

为了防止你有两种方法:

  1. target=_blank在您的表单标签中使用
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" target="_blank">
  1. 用于event.preventDefault();防止表单的默认操作,然后使用手动发送数据,fetch或者如果您使用 JQuery,您可能会使用ajax. (我将使用 fetch 标准 API)
document.getElementByTagName("form")[0].addEventListener('submit', function(event) {
  event.preventDefault();

  const url = 'https://randomuser.me/api';
  // The data we are going to send in our request
  const data = {
    name: 'Sara'
  }
  // The parameters we are gonna pass to the fetch function
  const fetchData = {
    method: 'POST',
    body: data,
    headers: new Headers()
  }
  fetch(url, fetchData)
    .then(function() {
      // Handle response you get from the server
    });
});

推荐阅读