我正在尝试向node.js服务器发出post请求,以便使用Fetch API向服务器提交一些数据。现在我想根据服务器返回的响应***显示成功消息***,但我无法这样做,因为每次我尝试这样做时页面都会刷新。我已经尝试了许多不同的方法来阻止这一点(例如。e.preventDefault(),将button更改为div,将button的类型更改为button而不是submit),但似乎什么都不起作用。请有人帮我出去。在这里发布我的HTML和Javascript代码。另外,我对网络开发非常陌生(只有2个月的经验),所以请你也告诉我,我所遵循的方法是对的还是错的。谢谢!
我在CSS部分使用语义UI
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
<link rel="stylesheet" href="./styles/styles.css">
</head>
<body>
<div class="ui fixed inverted menu">
<div class="ui container">
<a href="#" class="header item">
My Project
</a>
</div>
</div>
<div class="ui main text container">
<form class="ui loading form" id="main_form">
<div class="field">
<textarea name="message" id="otp_message" cols="30" rows="10"></textarea>
</div>
<div class="ui success message">
<div class="header">OTP Sent</div>
<p>You've successfully sent the OTP on Mobile Number</p>
</div>
<div class="ui center aligned grid container">
<div class="ui row">
<button type="submit" class="ui green button" id="btn_validate">Send</button>
</div>
</div>
</form>
</div>
</body>
<!-- <script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script> -->
<script src="./scripts/send_message.js"></script>
</html>
Javascript:
let id;
let otp;
function processUser() {
const parameters = location.search.substring(1);
id = (parameters.split("=")[1]);
let url = 'http://localhost:3030/ShowContacts?id=';
url += id;
let data;
fetch(url, {method:"GET"})
.then(response => {
if (response.status === 404) throw new Error('User not found');
return response.text();
})
.then(response => {
data = JSON.parse(response);
// document.getElementById('name').innerText += ' ' + jsonDATA.first_name + ' ' + jsonDATA.last_name;
// document.getElementById('phone_number').innerText += ' ' + jsonDATA.mobile_number;
generateOTP();
})
.catch(e => {
console.log(e.message);
});
}
processUser();
async function generateOTP() {
let url = 'http://localhost:3030/getOTP';
fetch(url, { method: "GET" })
.then(response => {
if (response.status === 404) throw new Error('Unable to generate otp');
return response.text();
})
.then(response => {
const jsonDATA = JSON.parse(response);
otp = jsonDATA.otp;
document.getElementById('main_form').classList.remove('loading');
document.getElementById('otp_message').value = `Hi. Your OTP is: ${otp} . Please do not share it with anybody else.`;
})
.catch(e => {
console.log(e.message);
})
}
const myForm = document.getElementById('main_form');
// const btn = document.getElementById('btn_validate');
document.forms['main_form'].addEventListener('submit', (event) => {
event.preventDefault();
let otpSent = false;
const message = document.getElementById('otp_message').value;
const raw = JSON.stringify({
id: id,
message: message,
otp: otp
});
const requestOptions = {
method: 'POST',
body: raw
};
const url = "http://localhost:3030/otpSent";
fetch(url, requestOptions)
.then(response => response.json())
.then(response => {
otpSent = response.success;
if (otpSent) {
let prevClassValue = myForm.getAttribute('class');
prevClassValue += " success";
myForm.setAttribute('class', prevClassValue);
}
})
.catch(error => console.log(error));
})
2条答案
按热度按时间xzlaal3s1#
我有下一个代码:
登录是我的自定义钩子的一个函数,但更简单,它只是通过获取发送确切的URL信息。顺便说一下,我明白了,页面刷新,这只是常见的行为形式与按钮.所以我在fetch之前添加了event.preventDefault()(这很重要)。
在您的情况下,你有从与按钮太,和刷新相应地去这一点。
zlwx9yxi2#
这是由于Live Server也在寻找.json文件中的更改。您可以通过更改Live Server的设置来修复它:进入VS代码中的扩展选项卡,查找Live Server,然后单击“设置”图标,然后单击“扩展设置”,然后向下滚动并单击“Live Server >设置:忽略文件”下的“在settings.json中编辑”,然后替换并添加: