標籤:class response ons onclick content div pre select 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‘].‘歲了‘; ?>
ajax原生post請求