reading javascript alert value from xml - javascript

I have a JavaScript function code where I want to alert.
function msg(x,y)
{
tempstr = x.value
if(tempstr.length>y)
{
alert(c_AcknowledgementText);
x.value = tempstr.substring(0,y);
}
}
Now I have an xml with below format:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<key name="c_ContactUsHeading">Contact Us</key>
<key name="c_AcknowledgementText">Comments can not be more than 250 characters.</key>
</root>
I want the JavaScript code so that the message shown in above alert can be read from above xml key name "c_AcknowledgementText".
I hope it is clear about my problem.

Basically, you want to use XMLHttpRequest. Not sure what you're trying to do with tempstr, etc., though.
function msg(x,y)
{
tempstr = x.value;
if(tempstr.length>y)
{
var req = new XMLHttpRequest();
req.open('GET', '/file.xml', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
{
var keys = req.responseXML.getElementsByTagName("key");
for(var i = 0; i < keys.length; i++)
{
var key = keys[i];
if(key.getAttribute("name") == "c_AcknowledgementText")
{
alert(key.textContent);
break;
}
}
}
else
alert("Error loading page\n");
}
};
req.send(null);
x.value = tempstr.substring(0,y);
}
}

First step is to get a DOM reference to the XML document. One way to do that is with Ajax. In this case, the server needs to respond with the Content-Type: text/xml header.
$.ajax({
type: "GET",
url: "/path/to/my.xml",
dataType: "xml",
success: function(doc){
var keys = doc.getElementsByTagName('key');
if (keys.length > 0) {
for (var i=0; i<keys.length; i++) {
if (keys[i].getAttribute('name') == 'c_AcknowledgementText') {
alert(keys[i].innerHTML);
}
}
}
}
});
You may need some additional error-handling, etc.

You have to parse the XML file for c_AcknowledgementText (either in JavaScript or using a server side language and storing it into JavaScript as the page loads).

Related

XMLHttpRequest - get value from URL and write it in a div

I have a div called totalvalue.
<div id="totalvalue"></div>
I wrote a function to get value from my PHP script (on the same server).
function totalvalue() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
totalvalue = (ajax5.responseText);
console.log(totalvalue);
document.getElementById("totalvalue").innerHTML = ajax5.responseText;
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
The php script does output a value.
Neither my console nor the div display the output.
This worked for me.
function test5() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
xxx5 = (ajax5.responseText);
console.log("this is the total value: "+xxx5);
if (xxx5 == 0) {
document.getElementById("totalvalue").innerHTML="Loading...";
} else {
document.getElementById("totalvalue").innerHTML="Total: "+xxx5;
}
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
I presume that where I write the div matter + there could have been an issue with the cache. I cannot tell for sure why the above just started working.
For simpler code, and better cross browser support, i would use jQuery.ajax like so:
$.ajax({
url: 'totalvalue.php',
success: function(data){
$('#totalvalue').html(data);
}
});
Read more about it in the documentation

Urls in creating chrome extension tabs do not work

I am creating a chrome extension which access a api and parses the json feed to get data. One of the data is a link and I want the link to be opened in a new tab. I use chrome.create.tabs to do it. But instead of opening a tab with specified url it opens like this
chrome-extension://app_id/%22http://www.twitch.tv/imaqtpie%22
Here is my popup.js
document.addEventListener('DOMContentLoaded', init);
function init(){
var elem = document.getElementById('Add');
elem.addEventListener('click',func);
}
function func(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.twitch.tv/kraken/search/streams?q=league%20of%20legends", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// innerText does not let the attacker inject HTML elements.
var qtpie=JSON.parse(xhr.responseText);
var display_name = JSON.stringify(qtpie.streams[0].channel.display_name);
var stream_status = JSON.stringify(qtpie.streams[0].channel.status);
var stream_url=JSON.stringify(qtpie.streams[0].channel.url);
var res = display_name+" : "+stream_status+"\n"+stream_url;
console.log(stream_url);
var a = document.createElement('a');
var linkText = document.createTextNode(res);
a.appendChild(linkText);
a.setAttribute('href', stream_url);
a.addEventListener('click', link_handler(stream_url));
document.getElementById("status").appendChild(a);
var magic=activateLinks();
// document.getElementById("status").innerText = res;
}
}
xhr.send();
}
function activateLinks()
{
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
(function () {
var ln = links[i];
var location = ln.href;
ln.onclick = function () {
chrome.tabs.create({active: true, url: location});
};
})();
}
}
function link_handler(url)
{
// Only allow http and https URLs.
if (url.indexOf('http:') != 0 && url.indexOf('https:') != 0) {
return;
}
chrome.tabs.create({url: url});
}
Here stream_url is the variable that stores the parsed url from json.
here is the json from which it is parsed from
"video_banner":null,
"background":null,
"profile_banner":null,
"profile_banner_background_color":null,
"partner":true,
"url":"http://www.twitch.tv/imaqtpie",
"views":91792487
i want the new tab to open http://www.twitch.tv/imaqtpie instead of chrome-extension://app_id/%22http://www.twitch.tv/imaqtpie
. Thanks in advance. Btw using <base href="http://" target="_blank"> does not work.
So the problem is for the url. Your url is improper when using chrome.tabs.create, because %22 indicates the character " in ASCII Encoding Reference. You should strip it off in the url when you get the element in html. Glad it helps!

Javascript function not found when moved to external file

I'm moderatley new to ASP.NET and very new to Javascript. I'm writing a ASP.NET UserControl. I had the following:
<head>
<title>Select Asset </title>
<script src="../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function CheckThenCloseActiveToolTip(supplierID) {
var radGrid = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList_ctl00');
var selectedItems = radGrid.get_masterTableView().get_selectedItems()
if (selectedItems == null || selectedItems.length == 0) return 'You must select an asset first';
else {
DoPartialPostBack('selectasset', selectedItems[0]._dataItem.Id);
CloseActiveToolTip();
}
}
function PopulateRooms(e) {
var idx = e.selectedIndex;
if (idx > -1) {
var dcId = JSON.stringify({ dataCenterId: e.options[idx].value });
var pageUrl = '/WebService/AVWebService.asmx';
$.ajax({
url: pageUrl + '/GetRooms',
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: dcId,
success: OnRoomsReceived,
error: OnErrorCall
});
}
else {
var ddlRooms = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
ddlRooms.disabled = true;
$('#ddlRooms').empty();
ddlRooms.options[0] = new Option('', '-1');
getAssets(0);
}
}
function OnRoomsReceived(result) {
var ddlRooms = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
if (result.d.length > 0) {
ddlRooms.disabled = false;
$('#ddlRooms').empty();
ddlRooms.options[0] = new Option('', '-1');
for (var i = 0; i < result.d.length; i++) {
ddlRooms.options[i + 1] = new Option(result.d[i].Name, result.d[i].Id);
}
}
if (result.d.length = 1)
ddlRooms.selectedIndex = 1;
getAssets(0);
}
function resetGridData() {
getAssets(0);
}
function getAssets(startAt) {
var cpId = document.getElementById('hfldCompanyId').value;
var pageUrl = '/WebService/AVWebService.asmx';
var tableView = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList').get_masterTableView();
var ddldc = document.getElementById('MainContent_SelectAssetGrid1_ddlDataCenter');
var dcIdx = ddldc.selectedIndex;
var dcId = '';
if (dcIdx > -1)
dcId = ddldc.options[dcIdx].value;
var ddlrm = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
var rmIdx = ddlrm.selectedIndex;
var rmId = '';
if (rmIdx > -1)
rmId = ddlrm.options[rmIdx].value;
var ddlStatuses = $find('ctl00_MainContent_SelectAssetGrid1_ddlStatuses';
var rbgAssetClass = document.getElementById('MainContent_SelectAssetGrid1_rbgAssetClass');
var ac = 0;
var rbgInputs = rbgAssetClass.getElementsByTagName('input');
for (var i = 0; i < rbgInputs.length; i++) {
if (rbgInputs[i].checked) {
ac = i;
}
}
var filters = [];
var fbs = document.getElementsByClassName('rgFilterBox');
for (var i = 0; i < fbs.length; i++)
if (fbs[i].value != '')
filters[filters.length] = { field: fbs[i].alt, value: fbs[i].value };
var params = JSON.stringify({ companyId: cpId,
startIndex: startAt,
maximumRows: tableView.get_pageSize(),
filterExpressions: filters,
dataCenterId: ddldc.options[ddldc.selectedIndex].value,
roomId: rmId,
Statuses: ddlStatuses._checkedIndices,
assetClass: ac
});
$.ajax({
url: pageUrl + '/GetSelectAssetData',
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: params,
success: updateGrid,
error: OnErrorCall
});
}
function updateGrid(result) {
var tableView = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList').get_masterTableView();
tableView.set_dataSource(result.d.gridData);
tableView.dataBind();
tableView.set_virtualItemCount(result.d.count);
}
function gridAssetList_Command(sender, args) {
args.set_cancel(true);
var pageSize = sender.get_masterTableView().get_pageSize();
var currentPageIndex = sender.get_masterTableView().get_currentPageIndex();
if (args.get_commandName() == 'Filter')
currentPageIndex = 0;
getAssets(pageSize * currentPageIndex);
}
function gridAssetList_Created(sender, args) {
var fbtns = document.getElementsByClassName('rgFilter');
for (var i = 0; i < fbtns.length; i++)
fbtns[i].style.visibility = 'hidden';
var fbs = document.getElementsByClassName('rgFilterBox');
for (var i = 0; i < fbs.length; i++)
fbs[i].onkeypress = applyFilter;
}
function applyFilter(args) {
if (args.keyCode == 13)
resetGridData();
}
</script>
This works most of the time, but if I'm loading the UserControl using Page.LoadControl(), it didn't always load the scripts correctly. For a couple of reasons (maybe poor ones) I thought I'd move the scripts to an external file.
<script src="../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="../Scripts/SelectAsset.js" type="text/javascript"></script>
There's no additional code or setup in the .js file, just
function CheckThenCloseActiveToolTip(supplierID) {
var radGrid = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList_ctl00');
var selectedItems = radGrid.get_masterTableView().get_selectedItems()
if (selectedItems == null || selectedItems.length == 0) return 'You must select an asset first';
...
But now I get a RunTime error that "function gridAssetList_Command" us undefined. That function is bound to a grid's OnCommand event in the page .
When I examine the page in Firebug, it doesn't list my .js file in the list of script files.
I'm loading my scripts in the . I didn't change them, just moved them. What am I missing?
MORE INFO:
It appears to be using different ClientIds when adding the functions to the controls. The error I'm getting drops be in a dynamic resource with the following:
Sys.Application.add_init(function() {
$create(Telerik.Web.UI.RadGrid, {"ClientID":"ctl00_MainContent_ctl03_gridAssetList","ClientSettings": ...
I'm going to try changing referenes to getElementByClass()
The best way to add javascript reference on asp.net web form is using ScriptManager on parent element or parent page such as a Master Page, And use ScriptManagerProxy on content pages and user controls.
Try use ScriptManager or combination of both to resolve your problem. Also use root application alias (~) for refer to file ex. src="~/Scripts/jquery-1.9.1.min.js"
So for simple way change your script reference to become:
<asp:ScriptManager ID="ScriptManagerProxy1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/Scripts/jquery-1.9.1.min.js" />
<asp:ScriptReference Path="~/Scripts/SelectAsset.js" />
</Scripts>
</asp:ScriptManager>
Update:
use for example:
$('table[id*="gridAssetList"]') for table with id = ctl00_gridAssetList_xx
$('input[id*="inputTxt"]') for input with id = ctl100_inputTxt
etc
to call html tag that rendered by asp.net component using jquery selector.
hi steve i think its shows error due to script source path please check that first then to verify the script loaded or not try this below code
if(typeof(yourfunction_name=='function')
{
// this code will make sure that the function is present in the page
//function exits do your functionality.
}else
{
alert('Script not loaded');
}

ajax request headers without jquery

I have created the following JavaScript function to load images of a vehicle, or load the alternate image if it is not available. The problem is that this page is 1kb, meanwhile it has to load the entire jquery library at 85+kb just for this one function. So my question is, is there some way to accomplish the same without having to load the jQuery library?
function GetImages() {
var Query = location.search;
//If query exists
if ((Query != "") && (Query != "?")){
var chunks = Query.split("=");
//If passed the right parameter
if (chunks[0] == "?unit") {
var Unit = chunks[1];
for (var i=1; i<11; i++) {
var unitimageURL = "/pics/"+Unit+"-"+i+".png";
$.ajax({
type: 'HEAD',
url: unitimageURL,
async: false,
success: function() {
$('.pictures').append("<img src="+unitimageURL+" width=150 height=90 alt='Unit "+Unit+" Picture "+i+"'> ");
if ((i == 4) || (i ==8)) {
$('.pictures').append("<br>");
}
},
error: function() {
$('.pictures').append("<img src=nopic2.png width=150 height=90 alt='Unit "+Unit+" Picture "+i+"'> ");
if ((i == 4) || (i ==8)) {
$('.pictures').append("<br>");
}
}
});
}
}
}
else {
alert("No query");
}
}
Yes, there is a way - the good old var oRequest = new XMLHttpRequest(); way!
Don't forget to to set all the needed callbacks, check response statuses and everything will be fine.
To create a HEAD request, just specify "HEAD" as parameter to .open() method.
You will also need document.createElement() to append the results to your page (or you may use .innerHTML property as well.
Also, documentation like this http://www.tutorialspoint.com/ajax/what_is_xmlhttprequest.htm may be handy.

hyperlinks aren't working, rss reader

hi i'm trying to build an rss reader using javascript. everything is up and running except the hyperlinks. I need to pass a variable that will hold the url for each list item. any advice would be appreciated. thanks.
xml ---------------------------
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>CNN RSS Feed</title>
<link>http://rss.cnn.com/rss/cnn_world.rss</link>
<description>Feeds from Army Public Affairs</description>
<pubDate>Tue, 11 May 2010 22:04:03 GMT</pubDate>
<language>en-us</language>
<item>
<title>U.S. ambassador to mark Hiroshima</title>
<link>http://www.cnn.com/2010/WORLD/asiapcf/08/05/japan.us.hiroshima.presence/index.html?eref=rss_world&utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+rss%2Fcnn_world+%28RSS%3A+World%29</link>
<pubDate>June 24, 2010</pubDate>
<source url="http://rss.cnn.com/rss/cnn_world.rss">CNN</source>
</item>
<item>
<title>Study: Nearly 1.3 million Mexicans in capital don't have running water</title>
<link>http://www.cnn.com/2010/WORLD/americas/08/04/mexico.water.supply/index.html?eref=rss_world&utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+rss%2Fcnn_world+%28RSS%3A+World%29</link>
<pubDate>13 July 2010</pubDate>
<source url="http://rss.cnn.com/rss/cnn_world.rss">CNN</source>
</item>
</channel>
</rss>
//JavaScript File
/OBJECTS
//objects inside the RSS2Item object
function RSS2Enclosure(encElement)
{
if (encElement == null)
{
this.url = null;
this.length = null;
this.type = null;
}
else
{
this.url = encElement.getAttribute("url");
this.length = encElement.getAttribute("length");
this.type = encElement.getAttribute("type");
}
}
function RSS2Guid(guidElement)
{
if (guidElement == null)
{
this.isPermaLink = null;
this.value = null;
}
else
{
this.isPermaLink = guidElement.getAttribute("isPermaLink");
this.value = guidElement.childNodes[0].nodeValue;
}
}
function RSS2Source(souElement)
{
if (souElement == null)
{
this.url = null;
this.value = null;
}
else
{
this.url = souElement.getAttribute("url");
this.value = souElement.childNodes[0].nodeValue;
}
}
//object containing the RSS 2.0 item
function RSS2Item(itemxml)
{
//required
this.title;
this.link;
this.description;
//optional vars
this.author;
this.comments;
this.pubDate;
//optional objects
this.category;
this.enclosure;
this.guid;
this.source;
var properties = new Array("title", "link", "description", "author", "comments", "pubDate");
var tmpElement = null;
for (var i=0; i<properties.length; i++)
{
tmpElement = itemxml.getElementsByTagName(properties[i])[0];
if (tmpElement != null)
eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
}
this.category = new RSS2Category(itemxml.getElementsByTagName("category")[0]);
this.enclosure = new RSS2Enclosure(itemxml.getElementsByTagName("enclosure")[0]);
this.guid = new RSS2Guid(itemxml.getElementsByTagName("guid")[0]);
this.source = new RSS2Source(itemxml.getElementsByTagName("source")[0]);
}
//objects inside the RSS2Channel object
function RSS2Category(catElement)
{
if (catElement == null)
{
this.domain = null;
this.value = null;
}
else
{
this.domain = catElement.getAttribute("domain");
this.value = catElement.childNodes[0].nodeValue;
}
}
//object containing RSS image tag info
function RSS2Image(imgElement)
{
if (imgElement == null)
{
this.url = null;
this.link = null;
this.width = null;
this.height = null;
this.description = null;
}
else
{
imgAttribs = new Array("url","title","link","width","height","description");
for (var i=0; i<imgAttribs.length; i++)
if (imgElement.getAttribute(imgAttribs[i]) != null)
eval("this."+imgAttribs[i]+"=imgElement.getAttribute("+imgAttribs[i]+")");
}
}
//object containing the parsed RSS 2.0 channel
function RSS2Channel(rssxml)
{
//required
this.title;
this.link;
this.description;
//array of RSS2Item objects
this.items = new Array();
//optional vars
this.language;
this.copyright;
this.managingEditor;
this.webMaster;
this.pubDate;
this.lastBuildDate;
this.generator;
this.docs;
this.ttl;
this.rating;
//optional objects
this.category;
this.image;
var chanElement = rssxml.getElementsByTagName("channel")[0];
var itemElements = rssxml.getElementsByTagName("item");
for (var i=0; i<itemElements.length; i++)
{
Item = new RSS2Item(itemElements[i]);
this.items.push(Item);
//chanElement.removeChild(itemElements[i]);
}
var properties = new Array("title", "link", "description", "language", "copyright", "managingEditor", "webMaster", "pubDate", "lastBuildDate", "generator", "docs", "ttl", "rating");
var tmpElement = null;
for (var i=0; i<properties.length; i++)
{
tmpElement = chanElement.getElementsByTagName(properties[i])[0];
if (tmpElement!= null)
eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
}
this.category = new RSS2Category(chanElement.getElementsByTagName("category")[0]);
this.image = new RSS2Image(chanElement.getElementsByTagName("image")[0]);
}
//PROCESSES
//uses xmlhttpreq to get the raw rss xml
function getRSS()
{
//call the right constructor for the browser being used
if (window.ActiveXObject)
xhr = new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest)
xhr = new XMLHttpRequest();
else
alert("not supported");
//prepare the xmlhttprequest object
xhr.open("GET",document.rssform.rssurl.value,true);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Pragma", "no-cache");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
if (xhr.responseText != null)
processRSS(xhr.responseXML);
else
{
alert("Failed to receive RSS file from the server - file not found.");
return false;
}
}
else
alert("Error code " + xhr.status + " received: " + xhr.statusText);
}
}
//send the request
xhr.send(null);
}
//processes the received rss xml
function processRSS(rssxml)
{
RSS = new RSS2Channel(rssxml);
showRSS(RSS);
}
//shows the RSS content in the browser
function showRSS(RSS)
{
//default values for html tags used
var imageTag = "<img id='chan_image'";
var startItemTag = "<div id='item'>";
var startTitle = "<div id='item_title'>";
var startLink = "<div id='item_link'>";
var startDescription = "<div id='item_description'>";
var endTag = "</div>";
//populate channel data
var properties = new Array("title","link","description","pubDate","copyright");
for (var i=0; i<properties.length; i++)
{
eval("document.getElementById('chan_"+properties[i]+"').innerHTML = ''");
curProp = eval("RSS."+properties[i]);
if (curProp != null)
eval("document.getElementById('chan_"+properties[i]+"').innerHTML = curProp");
}
//show the image
document.getElementById("chan_image_link").innerHTML = "";
if (RSS.image.src != null)
{
document.getElementById("chan_image_link").href = RSS.image.link;
document.getElementById("chan_image_link").innerHTML = imageTag
+" alt='"+RSS.image.description
+"' width='"+RSS.image.width
+"' height='"+RSS.image.height
+"' src='"+RSS.image.url
+"' "+"/>";
}
//populate the items
document.getElementById("chan_items").innerHTML = "";
for (var i=0; i<RSS.items.length; i++)
{
item_html = startItemTag;
item_html += (RSS.items[i].title == null) ? "" : startTitle + RSS.items[i].title + endTag;
item_html += (RSS.items[i].link == null) ? "" : startLink + RSS.items[i].link + endTag;
item_html += (RSS.items[i].description == null) ? "" : startDescription + RSS.items[i].description + endTag;
item_html += endTag;
document.getElementById("chan_items").innerHTML += item_html;
}
//we're done
//document.getElementById("chan").style.visibility = "visible";
return true;
}
var xhr;
<!-- html file -->
<html>
<head>
<script language="javascript" src="rssajax.js"></script>
<style type="text/css">
#chan_items { margin: 20px; }
#chan_items #item { margin-bottom: 10px; }
#chan_items #item #item_title {
font-weight: bold;
}
</style>
</head>
<body onload="getRSS()">
<form name="rssform">
<input name="rssurl" type="hidden" value="ChapRSS.xml">
</form>
<script language="javascript" src="rssajax.js"></script>
<div class="rss" id="chan">
<div id="chan_title"></div>
<div id="chan_description"></div>
<div id="chan_image_link"></div>
<div id="chan_pubDate"></div>
<div id="chan_copyright"></div>
</div>
</body>
</html>
<link>http://www.cnn.com/...?eref=rss_world&utm_source=...</link>
That is not well-formed XML, and hence not RSS. You must escape all literal ampersand symbols to &.
(It's not valid in HTML either. When you put a & in an href="..." attribute you must also escape it to &. The difference is browsers typically correct your mistake for you when they can; XML parsers won't.)
document.rssform.rssurl.value
Adding an ID on the <input> and using document.getElementById is less ambiguous than the old-school form collection access. Either way, that's a rather roundabout way of getting a value into script. Why not lose the form and simple pass the RSS filename as an argument into getRSS()?
this.title;
That doesn't do anything at all. None of the places you refer to a property like this have any effect; you are not creating members by doing this.
var properties = new Array("title", "link", ...
In general avoid the new Array constructor. The array literal syntax (var properties= ['title', 'link, ...]; is easier to read and doesn't have the constructor's unexpected behaviour for a single argument.
eval("this."+properties[i]+"=tmpElement.childNodes[0].nodeValue");
eval is evil. Never use it.
You can use square-bracket notation to access a property with a dynamic name. a.b is the same as a['b'], so:
this[properties[i]]= tmpElement.childNodes[0].nodeValue;
...
imgAttribs = new Array("url","title", ...
You haven't declared var imgAttribs so that's an accidental global. Same with Item in RSS2Channel. (Why the capital letter?)
eval("this."+imgAttribs[i]+"=imgElement.getAttribute("+imgAttribs[i]+")");
That won't work due to lack of quotes on the attribute name. You'll be getting getAttribute(url), and there's no variable called url -> error. Again, use square bracket property access to set the attribute and not eval.
eval("document.getElementById('chan_"+properties[i]+"').innerHTML = ''");
getElementById('chan_'+properties[i]) is fine, there is no point in doing that in an eval.
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Pragma", "no-cache");
Cache-Control and Pragma are typically HTTP response fields. They will not have the effect you expect in an HTTP request. If you want to ensure no caching occurs from the client side, use a ‘cachebuster’ method such as adding a random number or timestamp to the URL's query string.
innerHTML = curProp
Danger. Values you have fetched are arbitrary text strings and may contain HTML-special characters like < and &. If you write such strings to an element's innerHTML, you are likely to get broken results, and if they include third-party content you have just given yourself a cross-site-scripting security hole.
You can use textContent=... to set the content of an element without having to worry about HTML-escaping, however you then need to detect whether it's supported and fall back to IE's non-standard innerText property if it's not. A way that works on all browsers is to document.createTextNode(curProp) and append that text node to the element.
innerHTML= imageTag+" alt='"+RSS.image.description+ ...
You've got exactly the same problem with HTML-escaping here: if eg. the description contains <script>, you're in trouble. You can write an HTML-encoder, eg.:
function encodeHTML(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"').replace(/'/g, ''');
}
innerHTML= imageTag+' alt="'+encodeHTML(RSS.image.description)+ ...
But really, creating HTML from bits of string totally sucks. Use DOM methods instead:
var img= document.createElement('img');
img.src= RSS.image.url;
img.title= RSS.image.description;
img.width= RSS.image.width;
img.height= RSS.image.height;
document.getElementById('chan_image_link').appendChild(img);

Categories

Resources