我试图为一个Web应用程序创建一个登录页面,该页面使用JavaScript提取用户数据,然后使用Fetch API将数据发布到登录PHP脚本中,该脚本将对照数据库进行检查。我的提取请求返回错误,但可以使用公共URL。
JS文件: if(document.querySelector('#btn-submit')){
let frmLogin = document.querySelector('form');
//begin login process
function loginProcess() {
event.preventDefault();
const data = {
user: document.getElementById('user').value,
pass: document.getElementById('pass').value,
}
const options = {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
}
};
fetch('*url*', options)
.then(res => res.json())
.then(res => console.log(res));
}
}
我一直收到的错误是:console.log(res)的“ SyntaxError:JSON.parse:JSON数据的第1行第1列意外字符”。输出应该是输入,当我使用以下URL时它会打印出来:https://jsonplaceholder.typicode.com/posts
但当我使用网站的URL时(不包括在隐私目的中)
答案 0 :(得分:0)
我认为您的发布工作不错,但是您从服务器上获得的答案似乎不是json,请尝试以下操作进行最终提取:
fetch('*url*', options)
.then(res => res.text()) // use text instead of json
.then(res => console.log(res));