ajax解决get请求跨域问题

时间:2025-03-20 09:57:47

首先要知道Ajax默认是能获取到同源的数据,对于非同源的数据,Ajax默认是获取不到的。

同源:(1)协议相同;(2)域名相同;(3)端口相同

解决跨域问题的方法及原理:

     通过script标签,用script标签的src属性引入一个外部文件,这个外部文件是不涉及到同源策略的影响的。(同源策略是浏览器上为安全性考虑实施的非常重要的完全机制)

解决跨域问题:访问外部js文件或者访问外部PHP文件

步骤(1)访问外部js文件

(2)动态创建script标签传入动态参数

(3)给window增加属性进行方法定义

例子:访问淘宝提示词

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>淘宝提示词</title>
	<style>
		*{
			padding:0px;
			margin:0px;
		}
		.box{
			width:500px;
			height:300px;
			margin:100px auto;
			/*border: 1px solid #000;*/

		}
		.taobao{
			width:300px;
			height:40px;
		}
		.searchBtn{
			width:100px;
			height:40px;
		}
	</style>
	
</head>
<body>
	<div class="box">
		<input type="text" class="taobao" placeholder="请输入内容..."> 
		<input type="button" value="搜索" class="searchBtn">
		<ul></ul>
		<script>
			
			var searchBtn=("searchBtn")[0];
			=function () {
				var inpVal=("taobao")[0].value;

				(inpVal);
				var newscript=("script");
				="/sug?q="+inpVal+"&callback=lala";
				window["lala"]=function (data) {
					var liTag="";
					for(var i=0;i<;i++){
						var temp=[i];
						var tempSug=temp[0];
						liTag+="<li>"+tempSug+"</li>";
					}
					var ulTag=("ul")[0];
					=liTag;
				}
				var head=("head")[0];
				(newscript);

			}
			

		</script>
	</div>
		
</body>
</html>

post 请求的话,需要在服务器的头部加几句代码,不能直接用jsonp来解决。