AJAX--向服务器发送请求

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>

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...