Solved

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

Posted on 2010-08-14
5
720 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)

867 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

21 Experts available now in Live!

Get 1:1 Help Now