原生ajax与jquery下的ajax发送http请求(带头部Authriozation请求头)

昨天以为技术小伙伴问了我一个问题,想用js调用get请求。
https://market.aliyun.com/products/57126001/cmapi013650.html#sku=yuncode765000000 
第一反应是jquery下的ajax

<html>
<head></head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>	
<script>
//$(function(){ //此句代表整个html加载完了才执行,这里body都没东西,自然不需要
	$.ajax({
		url : 'http://toutiao-ali.juheapi.com/toutiao/index',
		type : 'get',
		headers: {
	              'Authorization' : 'APPCODE eef1833dbc5748cc86a6419ea0f92d9a'
	          },
		data : 'type=shehui',    // type: 默认返回的是头条,可以选择的,这个。
		dataType : 'json',
		success : function(msg){
			console.log(msg) 
		},
		error : function(err){
			alert('通信失败');
		}

	});
//});
</script>
<body></body>
</html>


后来又说要在命令行下执行,但$.get没法取http请求头,无奈,只能用原生的ajax

var ajax= new XMLHttpRequest();
ajax.open("GET","http://toutiao-ali.juheapi.com/toutiao/index");
ajax.setRequestHeader('Authorization','APPCODE eef1833dbc5748cc86a6419ea0f92d9a');
ajax.send();
ajax.onreadystatechange = function () {
	if(ajax.readyState==4){
		var txt=ajax.responseText;
		console.log(ajax.responseText); 
	}
}


以上是get方式,下面介绍下原生的post请求

//1. 实例化ajax
var ajax = new XMLHttpRequest();

//2.打开
ajax.open('post','05.php',true);

/2.1如果要使用post数据在send之前就要设置请求头
ajax.setRequestHeader('content-type','application/x-www-form-urlencoded');

//3.发送数据
ajax.send('name=小花猫&say=喵喵喵~~');

//4.添加监听事件
ajax.onreadystatechange = function(){
	//5. 在第4个状态  而且是status==200
	if(ajax.readyState==4 && ajax.status==200){
		console.log(ajax.responseText);
	}
}

后来又说要在windows cmd命令行下执行,彻底没辙了,好像是得装node,使用node.js,但是node好像不支持XMLHttpRequest,等解决了再来补充吧。。















  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值