前端发送get和post请求的三种方式

1. 用XMLHttpRequest对象发送请求

(1)get请求

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("div").innerHTML=xmlhttp.responseText;

  }
}
xmlhttp.open("GET","forwifestudy/testforget.php?info=123",true);
xmlhttp.send();         

注意:除了IE5和IE6之外的任意浏览器都可以创建一个XHR对象,在IE中,XHR是作为一个ActiveX对象实现的,在IE中这样创建对象:

 var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

new一个XHR对象之后,使用onreadystatechange函数来监听readyState属性的变化;
readyState属性表名了对象连接的状态:
0:未经初始化的,open还没有调用;
1:服务器连接已建立,open已经调用了;
2:请求已接受,也就是收到头信息了;
3:请求处理中,也就是收到响应主体了;
4:请求已完成,且响应就绪,也就是响应完成了;
请求成功之后我们就可以干一些事情了,比如讲服务器的相应数据显示出来等。(responseText是获取字符串形式的相应数据,responseXML是获取XML形式的相应数据)

document.getElementById("div").innerHTML=xmlhttp.responseText;

get发送请求变量名和值是写在url中的,像这样

xmlhttp.open("GET","forwifestudy/testforget.php?info=123",true);

(2)post请求

var request=new XMLHttpRequest();
request.onreadystatechange=function(){
    if(request.readyState===4 &&request.status===200){                      
        document.getElementById("div").innerHTML=request.responseText;
    }
    else{                       
    }
}
request.open("POST","forwifestudy/testforpost.php",true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send("info=123");

注意:post请求发送的数据并不是写在url中的,是嵌入到HTTP请求体中的,下面这句话必须在.open 和 .send中间

request.open("POST","forwifestudy/testforpost.php",true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send("info=123");

2. 用JQuery的 .get .post 方法发送请求

(1)get请求

$.get("forwifestudy/testforget.php",{info:123},function(data){
//请求成功时调用回调函数
    alert(data);
});

(2)post请求

$.post("forwifestudy/testforpost.php",{info:123},function(data,status){
alert("数据"+data+"\n状态"+status);

},"json");

和get请求一样,只是在后面加上数据的格式,比如“json”

2. 用JQuery的$.ajax方法发送请求

(1)get请求

$.ajax({
    url:"forwifestudy/testforget.php?info=123",
    datatype:"json",
    type:"GET",
    success:function(e){alert(e);},
    error:function(e){alert("失败");}
});

有成功时的回调函数和失败时的回调函数;

(2)post请求

$.ajax({
url:"forwifestudy/testforpost.php",                 
datatype:"json",
type:"post",
data:{info:123},
success:function(e){  //成功后回调
    alert(e);
},
error:function(e){   //失败后回调
    alert(e);
}           });

这两中方式发送请求差别在于,变量名和值的位置,根据type的类型(get还是post)

说明:我在此发送请求是不跨域的(也就是说我在本地的服务器上有这个PHP文件),如果要达到跨域的目的,就是在这个服务器上访问那个服务器上的数据,就需要在那个服务器的PHP文件中添加两句代码:

header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求  
header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); 

header("Access-Control-Allow-Origin: http://a.com"); // 允许a.com发起的跨域请求  
//如果需要设置允许所有域名发起的跨域请求,可以使用通配符 * 

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
发送GET请求的模板代码: ```javascript function sendGetRequest(url, params, callback) { var xhr = new XMLHttpRequest(); var queryString = ''; // 将参数转换为QueryString形式 if (params) { Object.keys(params).forEach(function(key) { queryString += key + '=' + params[key] + '&'; }); // 去除最后一个'&' queryString = queryString.slice(0, -1); } // 构建完整的URL if (queryString !== '') { url += '?' + queryString; } xhr.open('GET', url, true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // 请求成功,处理返回的数据 var responseData = JSON.parse(xhr.responseText); callback(responseData); } else if (xhr.readyState === 4 && xhr.status !== 200) { // 请求失败,处理错误信息 console.log('请求失败,错误码:' + xhr.status); } }; xhr.send(); } ``` 发送POST请求的模板代码: ```javascript function sendPostRequest(url, data, callback) { var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // 请求成功,处理返回的数据 var responseData = JSON.parse(xhr.responseText); callback(responseData); } else if (xhr.readyState === 4 && xhr.status !== 200) { // 请求失败,处理错误信息 console.log('请求失败,错误码:' + xhr.status); } }; xhr.send(JSON.stringify(data)); } ``` 以上两个模板分别用于发送GET和POST请求。在调用时需要传入URL、参数(对于GET请求)或数据(对于POST请求)、回调函数。回调函数用于处理请求成功后返回的数据。需要注意的是,在发送POST请求时,需要将数据转换为JSON字符串,并在请求头中设置Content-Type为application/json。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值