JS中的Ajax操作实例,get方式和post方式对比

来源:互联网 发布:人工智能的利弊800字 编辑:程序博客网 时间:2024/06/16 00:13

AJAX有另外一个名字叫XML HTTP请求,是微软首先创建的。

get和post方式对比

1、get是最常用的方式,get请求的参数数据会追加在请求URL中末尾,用查询语句的形式,即用?符合开始,后面跟着&符号链接起来的名称/值。如:http://www.somewhere.com/page.php?name1=value1&name2=value2&name3=value3
注意:
所有的名称和值都要经过编码后才能添加到URL中,使用encodeURIComponent()进行编码。
由于URL最长为2048字节即2KB,所以get方式不适合发送大量数据。

2、post是第二常见的方式,一般来说,post请求用于在表单中数据提交后的过程。因为post方式可以比get方式发送更多的数据,大约2GB,因为post方式发送的数据不是添加在URL中的。
post请求的参数也和get一样,要进行编码,并用&符号分割名称/值。同时还有设置HTTP请求头部。


Get方式 

Post方式

 function doRequestUsingGET(){

//1、创建XMLHttpRequest对象

if(window.ActiveXObject){  

//IE5、IE6浏览器

var xmlHttp = new ActiveXObject("Microsoft.XMLHttp");

}else if(window.XMLHttpRequest){ 

 //其他浏览器

var xmlHttp = new XMLHttpRequest();

}

//2、设置回调函数

 xmlHttp.onreadystatechange = function() {

 if(xmlHttp.readyState==4 && xmlHttp.status==200){

 var responseDiv = document.getElementById(serverResponse); responseDiv.innerHTML = decodeURI(xmlHttp.responseText);

      }

 }

//3、创建连接

var queryString = “name1=value1&name2=value2”;

var url = “test.php”

var data = url+”?”+queryString;

 xmlHttp.open("GET",data);

//4、发送数据

 xmlHttp.send(null);

 }

 

function doRequestUsingPOST(){

//1、创建XMLHttpRequest对象

if(window.ActiveXObject){  

//IE5、IE6浏览器

var xmlHttp = new ActiveXObject("Microsoft.XMLHttp");

}else if(window.XMLHttpRequest){  

//其他浏览器

var xmlHttp = new XMLHttpRequest();

}

//2、设置回调函数

 xmlHttp.onreadystatechange = function() {

 if(xmlHttp.readyState==4 && xmlHttp.status==200){

 var responseDiv = document.getElementById(serverResponse); responseDiv.innerHTML = decodeURI(xmlHttp.responseText);

      }

 }

//3、创建连接

var queryString = “name1=value1&name2=value2”;

var url = “test.php”

xmlHttp.open("POST",url);

//4、设置HTTP请求头部

xmlHttp.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded”)

//5、发送数据

 xmlHttp.send(queryString);

 }

 


0 0
原创粉丝点击