views:

214

answers:

3

I'm trying to use jQuery to parse the DHS Threat Level that they have in their XML file, but I can't seem to get it to work. I'm very new with Javascript and non-presentational jQuery, so I'm probably missing something obvious.

This is the XML file:

<?xml version="1.0" encoding="UTF-8" ?> 
<THREAT_ADVISORY CONDITION="ELEVATED" />

This is the Javascript I've written:

$(document).ready(function() {
    $.ajax({
     type     : 'GET',
     url      : 'http://www.dhs.gov/dhspublic/getAdvisoryCondition',
     dataType : 'xml',
     success  : function parseThreatLevel(xml) {
         var threatLevel = $(xml).find('threat_advisory').attr('condition');
         $('#nationalThreatLevel').append(threatLevel);
        }
    });
});

Below is the HTML I'm trying to use. Thanks in advance for any help or advice!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
    <head>
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'&gt;&lt;/script&gt;
    <script type='text/javascript' src='lib/parseThreatLevel.js'></script>
     <title>National Threat Level</title>
    </head>
    <body>
     <div id='nationalThreatLevel'></div>
    </body>
</html>
+4  A: 

All of your code is correct, but the problem is that you are making a cross domain request. The only way this will work with JavaScript / jQuery is if you can find a JSONP provider. Well, that or you write your own server side (PHP/ASP/ColdFusion/Something) to retrieve the XML and provide a local copy to be able to retrieve the XML using JavaScript.

Tony Miller
+1  A: 

XML is case-sensitive, isn't it? You might try using THREAT_ADVISORY and CONDITION. That is,

var threatLevel = $(xml).find('THREAT_ADVISORY').attr('CONDITION');
Matt
While this in and of itself won't solve the problem, it is another issue with Kerrick's code.
Paul Fisher
I had already tried changing case, I had just tried this solution last, so that's what got pasted. Whoops!
Kerrick
+4  A: 

For security reasons, javascript has no access to other domains. To bypass this, you need to add a script on your server that does have access to other domains - often times called a proxy.

PHP is a great option for many web-developers. What you would do is post the website url you want to hit to your local PHP script, it will then request that page and return the contents of it to your jQuery script which you can then parse for the data you desire.

Non-SO Solutions:

Stackoverflow Archive:

Jonathan Sampson
Thanks! This was extremely helpful. :D Not only did you give a solution, you also helped a poor old newbie like me learn. ;)
Kerrick
"For security reasons, javascript has no access to other domains." I suppose the national threat level would rise if it had access. :-D (This whole "threat level" business is beyond me...)
Tomalak