获取请求导致页面重新加载

时间:2021-06-08 15:55:23

标签: javascript html

在我的提取请求完成后,我的页面不断重新加载。我不希望在提交表单后重新加载页面。任何人都可以帮助解释为什么即使在使用 e.preventDefault() 之后我也会得到这种行为?您也可以为 JS 提出更好的格式提示,因为我是初学者并希望得到您的意见。我正在从使用 json-live-server 制作的假 REST API 中获取数据

HTML

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body class="body">
  <h1> Vaccination Centers</h1>
  <div id='app'>
    <form id='form'>
      <input type="text" id='enrollment' />
      <input type='text' id='session' />
      <button type="submit">submit</button>
  </form>
  </div>
<script type="module" src="main.js"></script>
</body>
</html>

JS

    let listArray

function getCenters () {
  fetch ('http://localhost:3001/students')
    .then(
      response => response.json()
    )
    .then(data => {
      listArray = data
      console.log(listArray)
    })
};

function init () {
  getCenters()
  const form = document.getElementById('form')
  form.addEventListener('submit', (e) => validate(e))
}

function validate (e) {
  console.log(e)
  e.preventDefault()
  let enrollment = document.getElementById('enrollment').value
  let student = listArray.find(s => s.enrollment.toString() === enrollment.toString())
  fetch ('http://localhost:3001/students/' + student.id, {
    method: 'PATCH',
    headers: {
      'Content-type': 'application/json; charset=UTF-8' // Indicates the content
    },
    body: JSON.stringify({ paidFee: true })
  }).then(document.getElementById('app').innerHTML = 'HELLO BITCHES')
}

window.onload = init

2 个答案:

答案 0 :(得分:0)

我们都同意,当 {{1} } 事件被触发。 OP 观察到的行为是对以下内容的破坏性覆盖:

e.preventDefault()

只需删除上面的内容,您就不应该看到重新加载页面的内容,但是如果您必须对这些婊子说“HELLO”,请改用 validate(e): >

<form>

以下示例具有用于 "submit" (.then(document.getElementById('app').innerHTML = 'HELLO BITCHES') ) 和 .insertAdjacentHTML() (.then(document.getElementBYId('app').insertAdjacentHTML('beforeBegin', 'HELLO BITCHES')) ) 事件的事件处理程序。如果点击 "submit",则使用 submitter(e),如果点击 "click",则使用 clicker(e)。还有一个记录器函数 (button#A) 将记录:

  • 事件类型......................................................{{1} }
  • 事件监听器 .innerHTML................................button#B
  • 按钮 .insertAdjacentHTML()................................................ .eventLogger(e)(来自 e.type 事件)
  • 如果默认设置被阻止.....#id

⃰实际上在那个位置是 e.currentTarget 但在这个上下文中没有区别

最好在整页模式下查看

#id
e.target.id
'click'

答案 1 :(得分:-1)

有些地方需要出席:

在您的原始脚本中,您使用异步提取来定义变量 listArray。不幸的是,您没有等待将值放入该变量中,而是直接继续。这种“等待”只能发生在异步函数中。因此:

  • 我创建了一个 async 函数,因为这样可以更轻松地处理包含 await 的 Promise。
  • 第一个将listArray填入所有注册学生以与输入的姓名进行比较
  • 需要在enrollment.value.trim().toLowerCase()上进行比较(不涉及.toString()
  • 如果找到了名称,则会发送第二个 fetch() 命令,将新信息“修补”到服务器
  • 来自服务器的返回数据然后以 JSON 格式显示在“成功消息”下。

const api='http://jsonplaceholder.typicode.com/users/';
document.getElementById('form').addEventListener("submit",validate);

async function validate(e) {
  e.preventDefault();
  const listArray=await fetch(api).then(r=>r.json());
  let student= listArray.find(s=>s.username.toLowerCase()===enrollment.value.trim().toLowerCase())
  if (student) {
   const d = await fetch(api+student.id, {method: 'PATCH',headers: {'Content-Type': 'application/json'},body: JSON.stringify({paidFee:true})}).then(r=>r.json());
   document.getElementById('app').innerHTML = '<div>HELLO BITCHES</div><pre>'+JSON.stringify(d,null,2)+'</pre>';
  } else console.log("This student does not exist in our list: "+listArray.map(s=>s.username).join(" "));
}
<h1> Vaccination Centers</h1>
<div id='app'>
  <form id='form'>
     <input type="text" id='enrollment' value="Bret">
     <input type='text' id='session'>
     <button type="submit">submit</button>
  </form>
</div>