jsonp跨域问题

什么是跨域?

  为页面安全考虑,页面中的JavaScript无法访问其服务器上的数据,即‘同源策略’,而跨域是通过某些手段来绕过同源策略限制,实现不同服务器间通信。

什么是jsonp?

  json是一种轻量级数据交互格式,而jsonp则是json的一种使用模式,通过这种模式实现数据的跨域获取。

如何实现跨域?

  1)、用script标签

  2)、用script标签加载资源是没有跨域问题

  3)、通过jsonp实现ajax跨域请求

注意:jsonp解决跨域时,必须要在script标签中定义一个函数,函数名与接口里后台数据的函数名(参数)相同,不然会出错

方法一: 在资源加载进来之前定义好一个函数,这个函数接收一个参数(数据),函数里面利用这个参数做一些事情
  然后需要时通过动态加载script标签加载对应远程文件资源,当远程的文件资源被加载进来的时候,就会去执行前面定义好的函数,并把数据当做这个函数的参数传进去

demo1案例,请求的数据格式为.txt文件

  txt文件的内容为:

fn([2,3,4]);

 html代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=8">
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<title>Document</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script>
		function fn(data){
			console.log(data);
		}
	</script>
	
</head>
<body>
	<button class="btn">ajax请求</button>
	Jsonp:json with padding
		1.script标签
		2.用script标签加载资源是没有跨域问题;
	方法一:	在资源加载进来之前定义好一个函数,这个函数接收一个参数(数据),函数里面利用这个参数做一些事情
		然后需要时通过动态加载script标签加载对应远程文件资源,当远程的文件资源被加载进来的时候,就会去执行前面定义好的函数,并把数据当做这个函数的参数传进去
<br>
</body>	
<script>
	$(function(){
		$('.btn').click(function(event) {
			// 当按钮点击时,再去加载资源
			var oScript = document.createElement('script');
			oScript.src = '2.txt';
			document.body.appendChild(oScript);
		});
		</script>
</html>

 运行结果为:

点击ajax请求后控制台打印出:

demo2,服务器端数据为getData.php,内容为:

<?php
$arr1 = array('111','2222','3333','444','555');
echo "fn(".json_encode($arr1).");";
?>

 html代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=8">
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<title>Document</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	
	<script>
	
		function fn(res){
			var html = '';
			var oul = document.getElementById('ul1');
			for(var i = 0;i < res.length;i++){
				html +='<li>'+res[i]+'</li>';
			}
			oul.innerHTML = html;
		}
	</script>
	
</head>
<body>
<button id="btn1">按钮1</button>
<ul id="ul1">
</ul>
</body>	
<script>
	$(function(){
		$('#btn1').click(function(event) {
			var myScript = document.createElement('script');
			myScript.src  = 'getData.php';
			document.body.appendChild(myScript);
		});
	});
</script>
</html>

运行结果为:

当点击按钮1时,获取php中的数据,并渲染到页面,结果如下:

demo3,服务器端接口为 data.php,其内容为:

<?php
$t = isset($_GET['t'])?$_GET['t']:'num';
$callback = isset($_GET['callback'])?$_GET['callback']:'fn1';//解决一个接口,在页面中多次调用问题
$arr1 = array('111','2222','3333','4444','5555','66668');
$arr2 = array('acs','bcs','ccs','dcs','ecs','fccs');
if ($t == 'num') {
	$data = json_encode($arr1);
	// echo "fn1(".$data.")";
}else{
	$data = json_encode($arr2);
	// echo "fn2(".$data.")";
}
echo $callback."(".$data.")";
?>

 html代码为:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=8">
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<title>Document</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script>
		function fn1(res){
			var html = '';
			var oul = document.getElementById('ul1');
			for(var i = 0;i < res.length;i++){
				html +='<li>'+res[i]+'</li>';
			}
			oul.innerHTML = html;
		}
		function fn2(res){
			var html = '';
			var oul2 = document.getElementById('ul2');
			for(var i = 0;i < res.length;i++){
				html +='<li>'+res[i]+'</li>';
			}
			oul2.innerHTML = html;
		}
		function fn3(res){
			var html = '';
			var oul3 = document.getElementById('ul3');
			for(var i = 0;i < res.length;i++){
				html +='<li>'+res[i]+'</li>';
			}
			oul3.innerHTML = html;
		}
	</script>
	
</head>
<body>
<button class="btn" >加载数字</button> <ul id="ul1"> </ul> <br> <button id="btn1" >按钮2加载字母</button> <ul id="ul2"> </ul> <button id="btn3" >按钮3加载数字</button> <ul id="ul3"> </ul>
<!-- 页面添加按钮,只需要在script中添加对应的函数即可 --> </body>
<script> $(function(){ $('.btn').click(function(event) { // 当按钮点击时,再去加载资源 var oScript = document.createElement('script'); oScript.src = 'data.php?callback=fn1'; document.body.appendChild(oScript); }); $('#btn1').click(function(event) { var myScript = document.createElement('script'); myScript.src = 'data.php?t=str&callback=fn2'; document.body.appendChild(myScript); }); $('#btn3').click(function(event) { var myScript = document.createElement('script'); myScript.src = 'data.php?callback=fn3'; document.body.appendChild(myScript); }); }); </script> </html>

 运行结果:

百度下拉列表实例 用到jsonp跨域问题:

接口地址是百度搜索的一个,地址为:https://www.baidu.com/su?wd=d&cd=movie

接口为:

maiov({q:"d",p:false,s:["dnf","地图","dota2","dhl","豆瓣","大众点评"]});

html代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
	<!-- <meta charset="UTF-8"> -->
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<title>Document</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<style>
		#q{ 300px;height: 30px;padding: 5px;border: 1px solid #f90;font-size: 18px;}
		#ul1{
			border: 1px solid #f90;
			border-top: none;
			 310px;
			margin:  0;
			padding:0;
			display: none;
		}
		.colors{text-decoration: none;color: #000;line-height: 30px;padding: 5px;text-align: left;display: block;/* 100%;*/box-sizing: border-box;}
		.colors:hover{
			color: white;
			background: #f90;
		}
	</style>
</head>
<script>
	function maiov(res){
		// console.log(res);
		var oul = document.getElementById('ul1');
		var html = '';
		if (res.s.length) {//表示与服务器连接成功
			oul.style.display = 'block';
			for(var i = 0;i < res.s.length; i++){
				html += '<li><a href="http://suggestion.baidu.com/su?wd='+res.s[i]+'">'+res.s[i]+'</a></li>'
			}
			oul.innerHTML = html;
		}else{
			oul.style.display = 'none';
		}
	}
	$(function () {
		// 获取到所有的元素
		$('#q').keyup(function(event) {
			// 鼠标抬起时,判断value值是否为空
			if ($('#q').val() != '') {
				var oScript = document.createElement('script');
				oScript.src = 'http://suggestion.baidu.com/su?wd='+$('#q').val()+'&cb=maiov';
				$('body').append(oScript);
			}
		});
	});
</script>
<body>
	<!-- 分析接口:用什么方式?ajax还是跨域;不同的接口,有不同的访问格式去处理 -->
	<input type="text" id="q" autocomplete="off">
	<ul id="ul1">
		<li><a class="colors" href="">1111111111</a></li>
		<li><a class="colors" href="">1111111111</a></li>
		
	</ul>
</body>
</html>

  运行结果为:

参考网址:http://www.php.cn/code/24227.html

原文地址:https://www.cnblogs.com/lvxisha/p/9747693.html