[英]Sending post request using ajax and load the data into the same php file
index.php
文件:
<?php
$content = file_get_contents("php://input");
$object = json_decode($content);
echo var_dump($object);
?>
<!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">
<title>Document</title>
</head>
<body>
<button onclick="hello()"> noice </button>
<script>
function hello() {
const data = {hello: "world"};
const xhr = new XMLHttpRequest();
xhr.open("POST", "index.php");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(data));
}
</script>
</body>
</html>
from index.php
sending a ajax post request with some data to the same index.php
and trying to view the fetched data from index.php
file but nothing happens. 但是文件被瀏覽器接收並且沒有更新。
我的問題是我做錯了什么? 以及如何實現這一目標?
無法在評論中寫很多...這是您的操作方式...
首先,在執行 var_dump 的地方,將該代碼塊放在 IF() 語句中並執行 exit(),這樣當腳本收到 POST 請求時,它只會轉儲變量並停止執行,否則您將收到ajax 響應中的完整頁面內容(包括所有 html)。
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$content = file_get_contents("php://input");
$object = json_decode($content);
echo var_dump($object);
exit();
}
?>
然后在 ajax 部分,處理響應,如..
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Do anything you want with => this.responseText
// If you want to update the whole view, you can do like
document.getElementsByTagName('body').item(0).innerHTML = this.responseText;
}
};
xhr.send(JSON.stringify(data));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.