I'm a AJAX newbie, I was wondering if I can use the .responseText method, to load the text from other website?

For example, how can I download the data from "http://www.weather.com/weather/today/Hong+Kong+China+CHXX0049" and display the data in my own way?

It seems that the .responseText/.responseXML does not work here...:-/

thanks for your kindly help!:)

It depends on the html tag displaying the text and its id or name for example lets say you got an text response which is HTML and the tag displaying this text you want to modify is a DIV tag with id "message" you can work with it like this.

// assuming the XMLHttpRequest is xhr
var responsestr=xhr.responseText;
// you have to include the gotten response on the page first, lets say a hidden div with the id "hidden"

document.getElementById("hidden").innerHtml=responsestr;
var wantedstr;

wantedstr=document.getElementById("message").innerHtml;
//then manipulate the text the way you want it

its kind of shady though but I hope it helps

<html>
	<title>AJAX return text</title>
	<head>
		<script type = "text/javascript">
			function getXMLHTTPRequest(){
				var req = false;
				try {
					req = new XMLHttpRequest();
				}catch(err1){
					try{
						req = new ActiveXObject("Msxml2.XMLHTTP");
					}catch(err2){
						try{
							req = new ActiveXObject("Microsoft.XMLHTTP");
						}
						catch(err3){
							req = false;
						}
					}
				}
				return req;
			}
			
			var http = getXMLHTTPRequest();
			
			function getServerText(){
				var myurl = "http://www.weather.com/weather/today/Hong+Kong+China+CHXX0049";
				http.open("GET", myurl, true);
				http.onreadystatechange = useHttpResponse;
				http.send(null);				
			}
			
			function useHttpResponse(){
				if( http.readyState == 4){
					var mytext = http.responseText;
					alert(mytext);
				}else{
					document.getElementById('test').innerHTML = 'Not fetched';
				}
			}
			
		</script>
	</head>
	<body onload="getServerText()">
		<div id='test'></div>		
	</body>
</html>>

thx meffe!

This is what I have, but the alert box just give me some blank msg.
It gives me "null" if I replace http.responseText with http.responseXML
What's wrong with my coding?

Member Avatar for fatihpiristine

nothing is wrong with your code. responseXML might give you null when the returned value from request is not valid XML.

it is better if you create an element in body with style="display: none" attribute then do the parsing from there as meffe suggested above.

I've written a simple html page called 'test.html' and it works!

<html>
	<head>
		<title>HelloWorld</title>
	</head>
	<body>
		<div id='hello'>Hello</div>		
	</body>		
</html>

All the html codes displayed correctly.
I just wondering why I cannot do this when I linked to some other sites outside.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.