天天看点

jquery利用雅虎YQL 做中间层进行跨域请求

废话不多说直接上代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<style>
		ul li{
			list-style: none;
		}
	</style>
	<body>
		<button>解梦</button> 
		<input type="text" />
		<ul>
			
		</ul>
	</body>
	<script type="text/javascript" src="js/jquery-2.1.0.js" ></script>
	<script>
		$("button").on("click",function(){
			var dream=$("input").val()
//在这个我们定义一下需要请求的地址
			var target="http://v.juhe.cn/dream/query?key=8194d647c67f88eedd63c&q="+dream
		$.ajax({
			type:"get",
//这里请求的是雅虎的yql地址
			url: 'http://query.yahooapis.com/v1/public/yql',
			async:true,
			dataType:"jsonp",
// 雅虎代理要求的数据格式
			 data: {    
                q: "select * from json where url=\'" + target+ "'",    
                //代理返回格式
                format: "json"    
           },    
			success:function(res){
				console.log(res)
				var theword=res.query.results.json.result
				console.log(theword)
				for (var i=0 ; i<theword.length ; i++) {
					if(theword[i].des==undefined){
						theword[i].des="预示为空"
					}else{
					$("ul").append("<li>梦见:"+theword[i].title+"</li><li>预示:"+theword[i].des+"</li>")
						
					}
					

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

继续阅读