【问题标题】:Open url with post method in background in javascript在javascript的后台使用post方法打开url
【发布时间】:2021-03-09 05:12:27
【问题描述】:
当用户尝试登录时,我想用 post 方法打开一个 (https://example.com/core/login),以便在登录页面的后台使用 post 方法将登录数据发送到 php 文件并使用 javascript 获取结果。
此 php 文件结果为 json 格式,我想告诉 javascript 中的“结果”是否“正常”:{'result':'ok','userid':'65363546'} 将用户重定向到仪表板,否则显示示例错误。
【问题讨论】:
-
请阅读How to Ask。一个简单的“我想要”在这里不被认为是一个合适的问题,你需要付出一些努力。
标签:
javascript
php
frontend
backend
【解决方案1】:
您可以使用 fetch api 或 axios 插件发出 post 请求,并检查响应结果是否等于 'ok'。在 true 条件下您可以使用 window.location.href = '/path/to/dashboard' 在 false 上您可以执行任何操作来生成错误消息。
const loginData = {
"email": "x@y.z",
"password": "xyz@password"
};
const headers = {
method: 'post',
body: JSON.stringify(loginData)
}
fetch('https://example.com/core/login', headers).then(function(response) {
return response.json();
}).then(function(data) {
if (data.result == 'ok') {
window.location.href = "/path/to/dashboard";
} else {
alert("Error: show a descriptive error");
}
});