ajax原生post請求


<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
<h1>ajax 發送post</h1>
	<input type="text"  value="" placeholder="請輸入你愛吃的菜" id='foodText'>
	<input type="button"  value="ajaxPost請求" id='btnAjax'>
</body>
</html>
<script type="text/javascript">
	document.querySelector("#btnAjax").onclick = function () {
		var ajax = new XMLHttpRequest();

		// 使用post請求
		ajax.open('post','ajax_post.php');

		// 如果 使用post發送數據 必須 設置 如下內容
		// 修改了 發送給 服務器的 請求報文的 內容
		// 如果需要像 HTML 表單那樣 POST 數據,請使用 setRequestHeader() 來添加 HTTP 頭。然后在 send() 方法中規定您希望發送的數據:
		ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		// 發送
		// post請求 發送的數據 寫在 send方法中 
		// 格式 name=jack&age=18 字符串的格式
		ajax.send('name=jack&age=998');

		// 注冊事件
		ajax.onreadystatechange = function () {
			if (ajax.readyState==4&&ajax.status==200) {
				console.log(ajax.responseText);
			}
		}
	}
</script>

  PHP文件

<?php 
	// 獲取 post的數據
	echo '你'.$_POST['age'].'歲了';
 ?>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM