Solved

Parse String or JSON response to get a DOM element from the string / response

Posted on 2010-08-14
5
718 Views
Last Modified: 2013-11-08
I am not too familiar with this.  I found a function on the Web that can make a cross domain query using jQuery and YSQL.  It seems to be working and returns everything from <body> to <body> in data.

What I want to do is actually edit the response in data so that it is equal to an element in the response.

e.g.

There is and element in the response that has this form:

 <table id="MainContentTable" cellpadding="0" cellspacing="0" width="100%">

... ....

</table>

I want the table tags and the innerHTML.

Is there a way to do that?  I'm not sure if data is simply a string, a JSON object, XML.  Seems like it should not be too hard.

// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {

	// If no url was passed, exit.
	if ( !site ) {
		alert('No site was passed.');
		return false;
	}

	// Take the provided url, and add it to a YQL query. Make sure you encode it!
	var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';

	// Request that YSQL string, and run a callback function.
	// Pass a defined function to prevent cache-busting.
	$.getJSON( yql, cbFunc );

	function cbFunc(data) {
	// If we have something to work with...
	if ( data.results[0] ) {
		// Strip out all script tags, for security reasons.
		// BE VERY CAREFUL. This helps, but we should do more.
		data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
		// If the user passed a callback, and it
		// is a function, call it, and send through the data var.
		if ( typeof callback === 'function') {
			callback(data);
		}
	}
	// Else, Maybe we requested a site that doesn't exist, and nothing returned.
	else throw new Error('Nothing returned from getJSON.');
	}
}

Open in new window

0
Comment
Question by:sscotti
  • 4
5 Comments
 
LVL 5

Expert Comment

by:KiasChaos83
ID: 33439615
You could do

alert($("#MainContentTable", $(data.results[0])).html());
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33440208
For the cbFunc function use something like this :


function cbFunc(data) {
		// If we have something to work with...
		if ( data.results[0] ) {
			// Strip out all script tags, for security reasons.
			// BE VERY CAREFUL. This helps, but we should do more.
			data = "<div>" + data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '') + "</div>";
			// If the user passed a callback, and it
			// is a function, call it, and send through the data var.
			if ( typeof callback === 'function') {
				callback(data);
			}
			$("#putTableHere").append( $(data).find("table[id='MainContentTable']") );
		}
		// Else, Maybe we requested a site that doesn't exist, and nothing returned.
		else throw new Error('Nothing returned from getJSON.');
	}

Open in new window

0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 33440216
test page :


<!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>Untitled Document</title>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script language="javascript">
	$(document).ready(function() {
//		requestCrossDomain("http://www.domain.com/path/to/page.php", cbFunc);
		var tbody = "<tr><td>HELLO</td></tr><tr><td><input type=\"text\" value=\"\"/></td></tr>"
		var json = {"results":["<html><head></head><body><h1>test</h1><table id=\"MainContentTable\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">" + tbody + "</table><h2>test</h2></body></html>"]};
		cbFunc(json);
	});
	// Accepts a url and a callback function to run.
	function requestCrossDomain( site, callback ) {
		// If no url was passed, exit.
		if ( !site ) {
			alert('No site was passed.');
			return false;
		}		
		// Take the provided url, and add it to a YQL query. Make sure you encode it!
		var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
		
		// Request that YSQL string, and run a callback function.
		// Pass a defined function to prevent cache-busting.
		$.getJSON( yql, cbFunc );
	}

	function cbFunc(data) {
		// If we have something to work with...
		if ( data.results[0] ) {
			// Strip out all script tags, for security reasons.
			// BE VERY CAREFUL. This helps, but we should do more.
			data = "<div>" + data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '') + "</div>";
			// If the user passed a callback, and it
			// is a function, call it, and send through the data var.
			if ( typeof callback === 'function') {
				callback(data);
			}
			$("#putTableHere").append( $(data).find("table[id='MainContentTable']"));
		}
		// Else, Maybe we requested a site that doesn't exist, and nothing returned.
		else throw new Error('Nothing returned from getJSON.');
	}

</script>
</head>
<body>
<div id="putTableHere"></div>
</body>
</html>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 33441334
work too : $("#putTableHere").append( $("#MainContentTable", data) );
function cbFunc(data) {
		// If we have something to work with...
		if ( data.results[0] ) {
			// Strip out all script tags, for security reasons.
			// BE VERY CAREFUL. This helps, but we should do more.
			data = "<div>" + data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '') + "</div>";
			// If the user passed a callback, and it
			// is a function, call it, and send through the data var.
			if ( typeof callback === 'function') {
				callback(data);
			}
			$("#putTableHere").append( $("#MainContentTable", data));
		}
		// Else, Maybe we requested a site that doesn't exist, and nothing returned.
		else throw new Error('Nothing returned from getJSON.');
	}

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 33451065
Thanks a lot for the points!
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now