JavaScript使用XMLHttpRequest 發送GET/Post 請求

本文介绍如何利用JavaScript中的XMLHttpRequest对象实现GET和POST请求,并提供了完整的示例代码。通过按钮触发请求,展示了如何设置请求头、发送请求及接收响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值