且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript使用XMLHttpRequest 發送GET/Post 請求

更新时间:2022-09-10 08:36:47

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE HTML>
<html>
<head>
<title>Demo</title>
<script type="text/javascript">
     
     var xmlHttp; 
     
    //XmlHttpRequest对象
    function createXMLHttpRequest() { 
    var xmlHttp; 
    if (window.XMLHttpRequest) {  //非IE浏览器 
        xmlHttp = new XMLHttpRequest(); 
        if (xmlHttp.overrideMimeType) 
            xmlHttp.overrideMimeType('text/xml'); 
    } else if (window.ActiveXObject) {  //如果是IE浏览器
        try { 
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 
        } catch (e) { 
            try { 
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
            } catch (e) { 
            
        
    
    return xmlHttp; 
   
    
    function getStatusBack(){ 
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200){ 
            var b = xmlHttp.responseText; 
            alert(b);
            console.log(b);
         
        
    
   function testGet(){
     
     xmlHttp = createXMLHttpRequest(); 
     var url = "http://xxx/xxx/xxx" 
     xmlHttp.open("GET", url, true);// 异步处理返回  
     xmlHttp.onreadystatechange = getStatusBack;   //设置回调函数
     xmlHttp.setRequestHeader("Content-Type",  "application/x-www-form-urlencoded;"); 
     xmlHttp.send();  //发送请求
    }
    function testPost(){
        var parameter = "tidList=1"
         var url = "http://xxx/xxx/xxx"; 
       xmlHttp = createXMLHttpRequest();
       xmlHttp.open("POST", url, true); 
         xmlHttp.onreadystatechange = getStatusBack; //设置回调函数 
             xmlHttp.setRequestHeader("Content-Type", 
             "application/x-www-form-urlencoded;"); 
             xmlHttp.send(); //发送请求
    }
     
 
</script>
</head>
         
<body>
 
        <button  onclick="testGet()">Test Get</button>
        <button  onclick="testPost()">Test Post</button>
</body>
</html>

  


本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/p/5952576.html,如需转载请自行联系原作者