一. 請(qǐng)求PHP接口
- 建立process.php文件扁誓,文件內(nèi)容為捞镰,判斷是否有g(shù)et傳送過(guò)來(lái)的name參數(shù)。即,前臺(tái)ajax在請(qǐng)求時(shí)悄泥,會(huì)給PHP后臺(tái)傳一個(gè)參數(shù)捣卤,參數(shù)的名字叫name祠挫,是以get的形式傳送過(guò)來(lái)的西饵。如果存在就將echo拼接出來(lái)的東西返回給ajax4.html文件
- ajax4.html中如何傳參給PHP呢?在open方法中的請(qǐng)求路徑中躺翻,路徑后面加上?問(wèn)號(hào)丧叽,再加上參數(shù)名稱和參數(shù)值,如果有多個(gè)參數(shù)以&連接公你。
- 操作原理就是踊淳,點(diǎn)擊按鈕后,html文件會(huì)將name=Henry這個(gè)參數(shù)傳給PHP文件,php文件再將其拼接的字符串返回給html文件迂尝,進(jìn)行展示脱茉。
二. 正常表單GET提交數(shù)據(jù)到PHP和ajax請(qǐng)求數(shù)據(jù)GET的不同
1. 正常表單form提交數(shù)據(jù)
- html文件,form表單action提交信息到process.php文件中垄开,運(yùn)用get方法獲取數(shù)據(jù)琴许。第一個(gè)input標(biāo)簽用于輸入我們的參數(shù)name,以傳給php文件溉躲。第二個(gè)input標(biāo)簽為提交按鈕榜田。
<h1>正常表單數(shù)據(jù)提交到PHP</h1>
<form action="process.php" method="GET">
<input type="text" name="name">
<input type="submit" value="提交">
</form>
- 這里php文件接收參數(shù)name,并判斷返回給html文件锻梳。
<?php
if(isset($_GET['name'])){
echo "GET:你的名字是".$_GET['name'];
}
?>
- 頁(yè)面正常顯示箭券,這里注意url從html文件跳轉(zhuǎn)到php文件并加上了?和參數(shù)
2. ajax請(qǐng)求數(shù)據(jù)唱蒸,可以在不刷新頁(yè)面的情況下拿到數(shù)據(jù)
<h1>Ajax請(qǐng)求數(shù)據(jù)</h1>
<form id="getForm">
<input type="text" name="name" id="name1">
<input type="submit" value="提交">
</form>
<br>
<script>
document.getElementById("getForm").addEventListener("submit",getForm);
function getForm(e){
e.preventDefault();
let name = document.getElementById('name1').value;
let xhr = new XMLHttpRequest();
xhr.open("GET","process.php?name="+name, true);
xhr.onload = function(){
console.log(this.responseText);
}
xhr.send();
}
</script>
- 頁(yè)面沒(méi)有跳轉(zhuǎn)邦鲫,參數(shù)于控制臺(tái)中輸出
!
三. 正常表單POST提交數(shù)據(jù)到PHP和ajax請(qǐng)求數(shù)據(jù)POST的不同
<h1>正常表單POST數(shù)據(jù)提交到PHP</h1>
<form action="process.php" method="POST">
<input type="text" name="name">
<input type="submit" value="提交">
</form>
<h1>Ajax請(qǐng)求數(shù)據(jù)POST</h1>
<form id="postForm">
<input type="text" name="name" id="name2">
<input type="submit" value="提交">
</form>
<script>
document.getElementById("postForm").addEventListener("submit",postForm);
function postForm(e){
e.preventDefault();
let name = document.getElementById('name2').value;
let params = "name="+name;
let xhr = new XMLHttpRequest();
xhr.open("POST","process.php", true);
//設(shè)置請(qǐng)求頭
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.onload = function(){
console.log(this.responseText);
}
xhr.send(params);
}
</script>
<?php
if(isset($_POST['name'])){
echo "POST:你的名字是".$_POST['name'];
}
?>
- form表單
- ajax
- get和post的區(qū)別在于,get將參數(shù)放在url中傳遞過(guò)去神汹,而post是以密文的形式傳送。所以將參數(shù)用send形式傳送過(guò)去古今。
- 如果以post請(qǐng)求的話屁魏,還需設(shè)置請(qǐng)求頭