问题描述
如何访问传递给 data.PHP 脚本的数据?我有以下设置:
index.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>Http Requests & JavaScript</title>
<link rel="stylesheet" href="app.css">
<script src="xhr.js" defer></script>
</head>
<body>
<section id="control-center">
<button id="get-btn">GET Data</button>
<button id="post-btn">POST Data</button>
</section>
</body>
</html>
xhr.js
const getBtn = document.getElementById('get-btn');
const postBtn = document.getElementById('post-btn');
const sendHttpRequest = (method,url,data) => {
const promise = new Promise((resolve,reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method,url);
xhr.responseType = 'json';
if (data){
xhr.setRequestHeader('Content-Type','application/json');
}
xhr.onload = () => {
resolve(xhr.response);
}
xhr.send(JSON.stringify(data));
});
console.log(promise);
return promise;
};
const getData = () => {
sendHttpRequest('GET','http://localhost/async/data.json').then(responseData => {
console.log(response);
});
};
const sendData = () => {
sendHttpRequest('POST','http://localhost/async/data.PHP',{
email: 'drcrocket@gmail.com',password: 'bowie'
}).then(responseData => {
console.log(responseData);
});
};
getBtn.addEventListener('click',getData);
postBtn.addEventListener('click',sendData);
data.PHP
<?PHP
$myJson = '{
"per_page":"6","total":"12","total_pages":"2","data":
[
{
"id":"1","email":"rdumdumle@gmail.com","first_name":"david","last_name":"escabar"
},{
"id":"2","email":"bluesky@gmail.com","first_name":"Willie","last_name":"Nelson"
}
]
}';
print_r($myJson);
//print_r($data);
//print_r($_POST);
?>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)