问题描述
利用服务 http://m.weather.com.cn/data/101240101.html 获取南昌天气信息,返回格式是 json ,但是利用jquery 解析的时候,IE 解析数据成功正常显示,FireFox chrome 下解析失败,各位帮忙看看是啥原因。json格式大概如下(可以通过上面链接查看 json 完全内容): {"weatherinfo":{"city":"南昌","city_en":"nanchang","date_y":"2010年9月1日","date":"庚寅年七月廿三","week":"星期三","fchh":"11","cityid":"101240101","temp1":"32℃~26℃",......"tempF1":"89.6℉~78.8℉",......"weather1":"多云转阵雨",.....}} 页面解析代码如下:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>获取天气</title> <style type="text/css"> body{font-size:14px;font-family:微软雅黑;background:#f6f6f6;text-align: center;} </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script><script type="text/javascript">jQuery(function($){getWeather();});function setWeather(tID, tCity, tTip, tWendu, tFengli , img1 , img2) {$("#jsCity").html("<a href='http://www.weather.com.cn/html/weather/" + tID + ".shtml' target=_bank>" + tCity + "</a>");var tqimg = "<img src='weatherimgs/"+img1+".gif'><img src='weatherimgs/"+img2+".gif'>";$("#jsWeather").html(tqimg + tTip + " " + tWendu);}function getWeather() {var weajs = "http://m.weather.com.cn/data/101240101.html";$.getJSON(weajs, function (objJson) {var cityname = objJson.weatherinfo.city; //南昌var id = objJson.weatherinfo.cityid; //101240101var cityinfo1 = objJson.weatherinfo.weather1; //天气var cityinfo2 = objJson.weatherinfo.weather2;var wd1 = objJson.weatherinfo.wind1;//风向var wd2 = objJson.weatherinfo.wind2;var fl1 = objJson.weatherinfo.fl1;//风力var fl2 = objJson.weatherinfo.fl2;var temp1 = objJson.weatherinfo.temp1;//温度var temp2 = objJson.weatherinfo.temp2;var img1 = objJson.weatherinfo.img1;//天气图标1var img2 = objJson.weatherinfo.img2;//天气图标2var img3 = objJson.weatherinfo.img3;var img4 = objJson.weatherinfo.img4;var index = objJson.weatherinfo.index;var index_d = objJson.weatherinfo.index_d;var index_xc = objJson.weatherinfo.index_xc;var index_uv = objJson.weatherinfo.index_uv;var date = objJson.weatherinfo.date;var date_y = objJson.weatherinfo.date_y;var imgtitle1 = objJson.weatherinfo.img_title1;var imgtitle2 = objJson.weatherinfo.img_title2;var imgsingle = objJson.weatherinfo.img_single;var imgtitlesingle = objJson.weatherinfo.img_title_single;setWeather(id, cityname, cityinfo1, temp1, wd1, img1, img2);});}</script> </head> <body><div><span id='jsCity'>南昌</span><span id='jsWeather'>loading...</span></div><div id="show"></div> </body></html> 页面运行后,IE 中解析正常 如下图, firefox chrome 却解析失败。
解决方案
问题并不是出在解析本身,而是跨域访问问题。这是基于安全的考虑。你需要在服务器端请求这个地址,并将请求结果返回到客户端的脚本中。否则是一个失败的请求,也就是说这时候$.getJSON的回调函数干脆不会执行,更谈不上解析了。
解决方案二:
"index_ls":"不太适宜"后面加一个“,”试试!
解决方案三:
是不是数据有问题?检查一下,我记得json数据格式最后有一个“,”,IE和Firefox会不一致。