原生ajax实现jsonp

jsonp的原理
主要是利用动态创建 script 标签请求后端接口地址,然后传递 callback 参数,后端接 callback,后端经过数据处理,返回 callback 函数 调用的形式,callback 中的参数就是 json

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta http-equiv="X-UA-Compatible" content="ie=edge" />
	<title>Document</title>
</head>
<body>
	<input type="" id="username" oninput="search()" />
</body>
<script src="jquery-3.4.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
	function search()
	{
		var wd=$("#username").val();
		//console.log(wd);
		getJson("https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+wd,'get')
	}
	function getJson(url,callback)
	{
		var script=document.createElement('script');
		script.type="text/javascript";
		script.src=url+'&cb='+callback;
		document.querySelector('head').appendChild(script);
	}
	function get(data)
	{
		console.log(data)
	}
</script>
</html>
发布了39 篇原创文章 · 获赞 46 · 访问量 2803

猜你喜欢

转载自blog.csdn.net/sslcsq/article/details/105072661