加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

AJAX--向服务器发送请求

发布时间:2020-12-16 02:11:46 所属栏目:百科 来源:网络整理
导读:1、使用XMLHttpRequest对象的open()和send()方法: xmlhttp.open("GET","test.txt",true); xmlhttp.send(); open(method,url,async) method:请求类型(GET或POST) url:文件在服务器上的位置 async:true(异步)或false(同步) send(string) string:仅

1、使用XMLHttpRequest对象的open()和send()方法:

xmlhttp.open("GET","test.txt",true);

xmlhttp.send();

open(method,url,async)

method:请求类型(GET或POST)

url:文件在服务器上的位置

async:true(异步)或false(同步)

send(string)

string:仅用于POST请求

2、GET和POST的使用场景

与POST相比GET更简单快捷,且在大部分情况下都可以使用,而当我们出现以下情况时,使用POST:

无法使用缓存文件时;

向服务器发送大量数据时;

发送包含未知字符的用户输入时。

3、GET请求例子

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+,Firefox,Chrome,Opera,Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6,IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/ajax/demo_get.asp",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>

</body>
</html>

4、POST请求例子

<html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+,Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6,IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("POST","/ajax/demo_post.asp",true); xmlhttp.send(); } </script> </head> <body> <h2>AJAX</h2> <button type="button" onclick="loadXMLDoc()">请求数据</button> <div id="myDiv"></div> </body> </html>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读