1:使用submit提交:
onsubmit用于提交前阻止表單提交,如果為false則提交,為true則不提交!
check為提交前的驗證函數,如果不符合就return false,阻止表單提交,下為樣文:
復制代碼
<form action="4.php" method="post" onsubmit="return check" enctype="multipart/form-data">//enctype設置文件上傳的格式(該格式為上傳文件的必要格式)
<input id="name" type="text" placeholder="請輸入姓名">
<input id="paw" type="text" placeholder="請輸入密碼">
<input type="file">
<input type="submit" value="提交">
</form>
復制代碼
復制代碼
<script>
check{
var name=document.getelementbyid("name");
var paw=document.getelementbyid("paw");
if(name==""&&paw==""){
return false;
}else{
return true;
}
}
</script>
復制代碼
2:使用ajax實現異步提交:
一:創建xmlhttprequest核心對象(老師要求必須默寫出來)
復制代碼
function getxhr{
var xhr=null;
if(window.xmlhttprequest){
xhr=new xmlhttprequest;//除ie8外的其他瀏覽器
}else{
xhr=new activexobject('microsoft.xmlhttp');//ie8瀏覽器
}
return xhr;
}
復制代碼
二:建立連接并提交(post)
復制代碼
<body>
<form action="3.php" method="post" id="myform" name="myform">
用戶名:<input type="text" id="user" name="user"><br>
密碼:<input type="text" id="paw" name="paw"><br>
<input type="button" value="提交" id="btn">
</form>
</body>
<script>
var btn=document.getelementbyid("btn");
btn.onclick=function{
var xhr=getxhr;
xhr.open("post","3.php");//與服務器建立連接
xhr.setrequestheader("content-type","application/x-www-form-urlencoded");//設置post的請求頭
var user=document.getelementbyid("user").value;//獲取到name值
var paw=document.getelementbyid("paw").value;//獲取到paw值
xhr.send("user="+user+"&paw="+paw);//客戶端向服務器端發送請求
xhr.onreadystatechange=function{//客戶端接受服務器端的響應
//保證服務器端響應的數據發送完畢
if(xhr.readystate==4){
//保證這次請求是成功的,狀態碼為200是成功
if(xhr.status==200){
//接受服務器端的數據
var data=xhr.responsetext;
//測試
console.log(data);
}
}
}
}
</script>
復制代碼
二:建立連接并提交(get)
復制代碼
<script>
var btn=document.getelementbyid("btn");
btn.onclick=function{
var xhr=getxhr;//創建xmlhttprequest對象
var user=document.getelementbyid("user").value;//獲取到name值
var paw=document.getelementbyid("paw").value;//獲取到paw值
xhr.open("get","3.php?user="+user+"&paw="+paw+");//與服務器建立連接
xhr.send(null);//客戶端向服務器端發送請求
xhr.onreadystatechange=function{//客戶端接受服務器端的響應
//alert(xhr.readystate);
//保證服務器端響應的數據發送完畢
if(xhr.readystate==4){
//保證這次請求是成功的,狀態碼為200是成功
if(xhr.status==200){
//接受服務器端的數據
var data=xhr.responsetext;
//測試
console.log(data);
}
}
}
}
</script>
復制代碼
注:send不管是post還是get都不能省略,get類型的send為send(null)并不能向服務器發送請求數據
3. jquery中的ajax提交:
比較常用的
$get(url,data,callback,type)
//url:提交地址 data:提交數據 callback:回調函數 type:指定從服務器端回來的數據格式,默認為html格式,其他還有xml,json。
//post和它一樣,只需將get修改為post即可。
不常用的
復制代碼
$ajax({
url:"4.php",//設置請求地址
type:"post",//設置請求方式
async:"true",//設置是否異步請求
data:{name:"david",age:"20"},//發送請求的數據。只能為key:value格式
success:function(data,textstatus){//成功后的回調函數
conso
你應該知道的 Apache 命令寧德網站優化應該對關鍵詞密度把控門頭溝企業網站設計需要遵循哪些原則?網站建設過程中不能忽略的5個要點網絡推廣時主要優化哪些方面?網站優化如何避免優化雷區?一個服務器放幾個網站比較好?香港服務器用來做官網合適嗎