客户端(前端)Ajax中Get请求和Post请求的区别

版权声明:未经本人允许,必须声明原文转载地址和作者! https://blog.csdn.net/liuchang19950703/article/details/87915928

我们在使用Ajax时,当我们向服务器发送数据时,我们可以采用Get方式请求服务器,也可以使用Post方式请求服务器.那么,Get请求和Post请求的区别到底在哪呢? 
GET请求 
get是最常见的请求,最常用于向服务器查询某些信息。必要时,可以将查询字符串参数追加到URL的末尾,以便将信息发送给服务器,对XHR而言,位于传入open( )方法的URL末尾的查询字符串必须经过正确的编码才行,即查询字符串的每个参数的名称和值都 必须使用encodeURIComponent()进行编码,然后才能放到URL的末尾,而且所有的名-值对都必须由&号分隔;

xhr.open( "get", "example.php?name1=value1&name2=value2",true );


下面这个函数整可以辅助向现有URL的末尾添加查询字符串参数:

function addURLParam(){
    url += ( url.indexOf("?") == -1 ? "?" : "&" );
    url += encodeURLComponent(name) + "=" + encodeURLComponent( value );
    return url;
}

POST请求

使用频率仅次于GET的是POST请求,通常用于向服务器发送应该被保存的数据。 
POST请求应该把数据作为请求的主体提交,其请求的主体可以包含非常多的数据,而且格式不限。 
POST请求必须设置Content-Type值为application/x-form-www-urlencoded;如果不设置Content-Type 头部信息,那么发送给服务器的的数据就不会出现在$_POST超全局变量中。 
发送请求时POST请求在使用send方法时,需赋予其参数; 

总结:
Get请求和Post请求的区别 
(1)使用Get请求时,参数在URL中显示,而使用Post请求,则不会显示出来; 
(2)Post传输的数据量大,可以达到2M,而Get方法由于受到URL长度的限制,只能传递大约1024字节. 
(3)Get请求请求需注意缓存问题,Post请求不需担心这个问题; 
(4)Post请求必须设置Content-Type值为application/x-form-www-urlencoded; 
(5)发送请求时,因为Get请求的参数都在url里,所以send函数发送的参数为null,而Post请求在使用send方法时,却需赋予其参数; 
(6)GET方式请求的数据会被浏览器缓存起来,因此其他人就可以从浏览器的历史记录中读取到这些数据,例如账号和密码等。在某种情况下,GET方式会带来严重的安全问题。而POST方式相对来说就可以避免这些问题。 
下面用代码来说明两者的区别: 

GET请求:

function getMethod(){

    var xhr = new createXHR();

    var userName = document.getElementById("userName").value;
    var age = document.getElementById("age").value;

    //添加参数,以求每次访问不同的url,以避免缓存问题
    xhr.open( "get", "example.php?userName=" + encodeURTComponent( userName ) + "&age=" + encodeURTComponent( age ) + "&random=" + Math.random(), true );

    xhr.onreadystatechange = function(){

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

            document.getElementById("result").innerHTML = xhr.responseText;
        }
    }

    //发送请求,参数为null
    xhr.send( null );
}


POST请求:

function postMethod(){

    var xhr = new createXHR();

    var userName = document.getElementById("userName").value;
    var age = document.getElementById("age").value;
    var data = "userName=" + encodeURTComponent( userName ) + "&age=" + encodeURTComponent( age );

    //不用担心缓存问题
    xhr.open( "post", "example.php", true );

    //必须设置,否则服务器端收不到参数
    xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

    xhr.onreadystatechange = function(){

        if( xhr.readyState = 4 && xhr.status == 200 ){
            document.getElementById("result").innerHTML = xhr.responseText;
        }
    }

    //发送请求,要data数据
    xhr.send( data );

}

猜你喜欢

转载自blog.csdn.net/liuchang19950703/article/details/87915928