1/02/2012

Add weather panel in website(Create Request in JSP)

Sometimes, we need to create request in jsp to retrieve information from other server.


For example, if we want to use google weather api to add one weather panel in our website.


The simple realization is:





01 function createRequest() {
02
03     var request;
04
05     try {
06
07         request = new XMLHttpRequest();
08
09     } catch (trymicrosoft{
10
11         try {
12
13             request = new ActiveXObject("Msxml2.XMLHTTP");
14
15         } catch (othermicrosoft{
16
17             try {
18
19                 request = new ActiveXObject("Microsoft.XMLHTTP");
20
21             } catch (failed{
22
23                 request = false;
24
25             }
26
27         }
28
29     }
30
31     if (!request)
32
33         alert("Error initializing XMLHttpRequest!");
34
35     return request;
36
37 }


01 function createMarkerWeather(request){
02
03     var str="http://localhost:8080/MTA/";
04
05     var strURL="http://www.google.com/ig/api?weather=new+york,ny&hl=en";
06
07     request.open("GET",strURL,false);
08
09     request.send();
10
11     var myXD = new ActiveXObject("MSXML2.DOMDocument");
12
13     myXD.loadXML(request.responseText);
14
15     var myCity;
16
17     var myDate;
18
19     var myCondition;
20
21     var myTemp;
22
23     var myHumidity;
24
25     var myHigh;
26
27     var myLow;
28
29     var pic;
30
31     var informationNodes = myXD.getElementsByTagName("xml_api_reply/weather")[0].childNodes;
32
33     var strNodes = informationNodes[0].childNodes;
34
35     myCity = strNodes[0].getAttribute("data");
36    
37     myDate = strNodes[4].getAttribute("data");
38
39     strNodes = informationNodes[1].childNodes;
40
41     myCondition = strNodes[0].getAttribute("data");
42
43     myTemp = strNodes[2].getAttribute("data");
44
45     myHumidity = strNodes[3].getAttribute("data");
46     pic = strNodes[4].getAttribute("data");
47     pic = "http://www.google.com" + pic;
48    
49     strNodes = informationNodes[2].childNodes;
50
51     myLow = strNodes[1].getAttribute("data");
52
53     myHigh = strNodes[2].getAttribute("data");
54     var l = "o";
55    
56     document.getElementById("date").innerText = myDate;
57    
58     document.getElementById("weather_pic").innerHTML = "<img src='"+pic+"'/>";
59     //  document.getElementById("weather_city").innerHTML = myCity;
60     document.getElementById("weather_temp").innerHTML = "H:&nbsp;" + myHigh +l.sup()+"F"+"<br>"+"L:&nbsp" + myLow+l.sup()+"F";
61
62 //return  str;
63
64 }

In the main function, just needs to call:

var request = createRequest();
createMarkerWeather(request);

Test under IE8, works fine.

No comments:

Post a Comment