JS原生Ajax操作(XMLHttpRequest)


JS原生Ajax操作(XMLHttpRequest)

GET請求

復制代碼
 1 var xmld=new XMLHttpRequest();
 2 xmld.open("GET","wan.php"+"?dd1=dong11&dd2=dong22"); //打開頁面
 3 xmld.setRequestHeader("dh","donghhhh");//設置請求頭
 4 xmld.send(null); //發送數據需要手動在url添加
 5 xmld.onreadystatechange=function(){ 
 6 if(xmld.readyState == 4){
 7     //獲取返回數據
 8     alert(xmld.getResponseHeader("Server"));//獲取響應頭
 9     alert(xmld.status+"--"+xmld.statusText);//得到如200:ok、404:Not Found 等等
10     alert(xmld.responseText); //得到字符串
11     //var xx=xmld.responseXML //得到HTML對象
12         }
13 };
復制代碼

POST請求

復制代碼
 1 var xmld=new XMLHttpRequest();
 2 xmld.open("POST","wan.php"); //打開頁面
 3 xmld.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//設置請求頭
 4 xmld.send("dd1=dong11&dd2=dfikij"); //發送數據
 5 xmld.onreadystatechange=function(){ 
 6     if(xmld.readyState == 4){
 7     //獲取返回數據
 8     alert(xmld.getResponseHeader("Server"));//獲取響應頭
 9     alert(xmld.status+"--"+xmld.statusText);//得到如200:ok、404:Not Found 等等
10     alert(xmld.responseText); //得到字符串
11     //var xx=xmld.responseXML //得到HTML對象
12     }
13 };
復制代碼

兼容性問題

if(XMLHttpRequest){
    //系列操作
}else{
    alert("瀏覽器不支持");
}

利用iframe模擬ajax

實現表單提交的返回結果在iframe中進行顯示,實現主頁面不刷新效果,也可以模擬上傳文件,推薦使用,兼容性最好

復制代碼
 1 <iframe id="ifd" name="dongff"></iframe>
 2 <form action="wan.php" method="post" target="dongff">
 3 <input type="text" name="dd1">
 4 <input type="text" name="dd2">
 5 <input type="submit" onClick="subd()">    
 6 </form>
 7 //獲取返回內容
 8 <script src="jquery-3.3.1.min.js"></script>
 9 <script>
10 //在點擊提交按鈕時給iframe添加加載完畢事件    
11 function subd(){
12     //等待iframe內容加載完畢時進入
13     $("#ifd").on('load',function(){
14         //得到iframe的內容
15         var ifdtext=$("#ifd").contents().find("body").text();
16         alert(ifdtext);
17     });
18 }
19 </script>
復制代碼

基於jquery的ajax

Get請求,參數(URL,數據,回調函數)

$.get("wan.php",{namex:"myname",passwd:"123"},function(datax){
    $("p").text(datax);//datax為返回的數據
});

Post請求,參數與get一致

$.post("wan.php",{namex:"myname",passwd:"123"},function(datax){
    $("p").text(datax);//datax為返回的數據
});

加載HTML碎片,返回結果會覆蓋掉id為div1id標簽的內容

$("#div1id").load("uu.html",function(a,b,c){
if(b=="error"){
    $("#div1id").text("加載失敗");
    }
});

結合版:

復制代碼
 1 $.ajax({
 2     url:"wan.php",
 3     type:"POST",
 4 //headers:{"dongh":"dongssssss"}, //設置請求頭,涉及跨域時不要進行設置
 5     data:{"xx":123456,"user":"dddd"},
 6     success:function (data) {
 7         alert(data);
 8     },
 9     error: function (XMLHttpRequest, textStatus, errorThrown) {
10         // 狀態碼
11         alert(XMLHttpRequest.status);
12         // 狀態
13         alert(XMLHttpRequest.readyState);
14         // 錯誤信息
15         alert(textStatus);
16     }
17 
18 });
復制代碼

Ajax的跨域請求

如果在瀏覽器控制台看到類似如下的錯誤,表示存在跨域請求數據,即兩個網頁不是在同一個服務器上

Access to XMLHttpRequest at 'http://193.112.87.66/add.php?namex=myname&passwd=123' from origin 'http://192.168.43.21:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

解決方法如下,在訪問的頁面中添加響應頭內容

復制代碼
1 <?php 
2 // 指定允許其他域名訪問
3 header('Access-Control-Allow-Origin:*');
4 // 響應類型
5 header('Access-Control-Allow-Methods:POST');
6 // 響應頭設置
7 header('Access-Control-Allow-Headers:x-requested-with,content-type');
復制代碼

異步文件上傳

自定義文件上傳按鈕(點擊試試效果):

東文件

利用頁內標簽定位浮動,實現等大的input標簽浮於div標簽之上,並將自身透明度設置為零,span的標簽為顯示的文字

1 <div style="height: 50px;width: 80px;text-align: center;line-height: 50px;position: relative">
2 <span>東文件</span>
3 <input type="file" id="infileid" style="height: 50px;width: 80px;position: absolute;opacity: 0; bottom: 0px;left: 0px;top: 0px;right: 0px">
4 </div>

原生ajax文件上傳

復制代碼
 1 function subd(){
 2       
 3     var fileobjx=document.getElementById("infileid").files[0];//得到文件對象
 4     //創建form表單對象
 5     var formobjx=new FormData();
 6     formobjx.append("namexx","dong111");
 7     formobjx.append("dongfile",fileobjx);
 8     
 9     var xmld=new XMLHttpRequest();
10     xmld.open("POST","wan.php"); //打開頁面
11     xmld.send(formobjx); //發送form數據
12     xmld.onreadystatechange=function(){ 
13     if(xmld.readyState == 4){
14     alert(xmld.responseText); //得到字符串
15     }
16 };
復制代碼

Jquery的ajax文件上傳

 1 function subd(){
 2     var fileobjx=document.getElementById("infileid").files[0];//得到文件對象
 3     //創建form表單對象
 4     var formobjx=new FormData();
 5     formobjx.append("namexx","dong111");
 6     formobjx.append("dongfile",fileobjx);
 7     $.ajax({
 8     url:"wan.php",
 9     type:"POST",
10     data:formobjx,
11     processData: false,
12     contentType: false,
13     success:function (data) {
14         alert(data);
15     },
16     error: function (XMLHttpRequest, textStatus, errorThrown) {
17         // 錯誤信息
18         alert(textStatus);
19     }
20 
21    });
22 
23 };

 

轉自東小東博客園:

https://www.cnblogs.com/dongxiaodong/p/10422403.html

 


免責聲明!

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



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