您的位置:首页 > 其它

AJAX--向服务器发送请求

2014-12-06 09:33 162 查看
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+, 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("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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: