ajax无刷新获取天气信息

本文介绍了一种使用PHP作为代理服务器来解决AJAX跨域请求问题的方法,并提供了完整的HTML和PHP代码示例。此方案适用于需要从不同域获取数据的前端应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

浏览器由于安全方面的问题,禁止ajax跨域请求其他网站的数据

解决:利用本域php代理间接获取weather.php

<?php
header("content-type:text/html;charset=utf-8");
//php代理获取天气信息
//跨域请求
//天气预报接口
$url = "http://www.weather.com.cn/data/sk/101010100.html";
$cont = file_get_contents($url);
echo $cont;
?>
ajax通过php代理获取天气信息

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"  >
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
	<title>ajax</title>
	<style type="text/css">
	</style>
	<script type="text/javascript">
		function getWeather(){
				var xhr = new XMLHttpRequest();
				var s = "";
				xhr.onreadystatechange = function(){
					if(xhr.readyState==4){
						alert(xhr.responseText);
						eval("var info="+xhr.responseText);
						s += "城市:"+info.weatherinfo.city+" "; 
						s += "温度:"+info.weatherinfo.temp+" "; 
						s += "风向:"+info.weatherinfo.WD+" "; 
						s += "风力:"+info.weatherinfo.WS; 
					}
					document.getElementById("weather").innerHTML = s;
				}
				xhr.open('get','./weather.php');

				xhr.send(null);
				//阻止浏览器默认动作 跳转
				return false;
	}
	</script>
</head>
<body>
<h2>ajax无刷新获取天气信息</h2>
	<input type="submit" value="获取天气" οnclick="getWeather()"></input>
	<div id="weather"></div>
	<hr/>
	<iframe width="420" scrolling="no" height="60" frameborder="0" allowtransparency="true" src="http://i.tianqi.com/index.php?c=code&id=12&icon=1&num=5"></iframe>
</body>	
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值