昨天以为技术小伙伴问了我一个问题,想用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,等解决了再来补充吧。。