简体   繁体   中英

AJAX http GET request

I'm currently teaching myself some AJAX through jQuery.

I've written a straight forward get request to load in data from an xml file into a section with a class of container.

Here is my html file:

<!DOCTYPE html>
<html lang="en">
<head>

</head>
<body>

<section class="container">

</section>


<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8" async defer></script>
<script src="xmlFeed.js" type="text/javascript" charset="utf-8" async defer></script>
</body>
</html>

I am using a local xml file after i created to dummy post on a WordPress site and got the feed.

Here is the xml file:

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
    >

<channel>
    <title>Biz-Tech.ie &#187; Biz-Tech News</title>
    <atom:link href="http://www.biz-tech.ie/category/biz-tech-news/feed/" rel="self" type="application/rss+xml" />
    <link>http://www.biz-tech.ie</link>
    <description></description>
    <lastBuildDate>Sat, 11 Oct 2014 17:39:16 +0000</lastBuildDate>
    <language>en-US</language>
        <sy:updatePeriod>hourly</sy:updatePeriod>
        <sy:updateFrequency>1</sy:updateFrequency>
    <generator>http://wordpress.org/?v=4.0</generator>
    <item>
        <title>News</title>
        <link>http://www.biz-tech.ie/news/</link>
        <comments>http://www.biz-tech.ie/news/#comments</comments>
        <pubDate>Sat, 11 Oct 2014 17:39:16 +0000</pubDate>
        <dc:creator><![CDATA[Michael]]></dc:creator>
                <category><![CDATA[Biz-Tech News]]></category>

        <guid isPermaLink="false">http://www.biz-tech.ie/?p=170</guid>
        <description><![CDATA[Output Box &#8211; Random strings/passwords will display here. Load objects used for random string generation into the &#8220;Object Input Box&#8221; above. Objects above can be characters, words, sentences, etc. Test by clicking the &#8220;Generate random strings&#8221; button above to generate 10, 14 character, random strings from the default input objects. NOTICE: Tool uses Javascript method Math.random() pseudorandom generator to obtain [&#8230;]]]></description>
                <content:encoded><![CDATA[<p>Output Box &#8211; Random strings/passwords will display here.<br />
Load objects used for random string generation into the &#8220;Object Input Box&#8221; above. Objects above can be characters, words, sentences, etc.<br />
Test by clicking the &#8220;Generate random strings&#8221; button above to generate 10, 14 character, random strings from the default input objects.<br />
NOTICE: Tool uses Javascript method Math.random() pseudorandom generator to obtain random string. Do not use for critical random results.<br />
Privacy of Data: This tool is built-with and functions-in Client Side JavaScripting, so only your computer will see or process your data input/output.</p>
]]></content:encoded>
            <wfw:commentRss>http://www.biz-tech.ie/news/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>
        </item>
    </channel>
</rss>

And finally here is the ajax GET request along with a function to parse the xml into the container section in my html:

 $(doccument).ready(function() {
   $.ajax({
      type:"GET",
      url:"feed.xml",
      dataType:"xml",
      success:xmlParser
   });
});

function xmlParser(xml) {
   $(xml).find("item").each(function(){
      $("#container").append('<h3>'+ $(this).find("title").text()+'</h3><br />'
         '<a href="'+ $(this).find("link").text()+'></a>'
         '<p>'+ $(this).find("description").text()+'</p>'
         '<p><h5>Author: '+ $(this).find("dc:creator").text()+'</h5></p>'
         );
   });
}

The function isn't working and for the life of me I have no idea why as I can see an syntax errors. Any advice would be greatly appreciated. Thanks.

A few problems with your code.

1). The way you are concatenate strings in javascript is not correct. Use this syntax:

   $(xml).find("item").each(function(){
      $(".container").append('<h3>'+ $(this).find("title").text()+'</h3><br />' +
         '<a href="'+ $(this).find("link").text()+'"></a>' +
         '<p>'+ $(this).find("description").text()+'</p>' +
         '<p><h5>Author: '+ $(this).find('dc\\:creator, creator').eq(0).text()+'</h5></p>'
         );
   });

Note + operator, it is used for string concatenation.

2). One more problem. You missed a closing quote in link construction string, which breaks HTML and hides all subsequent content:

'<a href="' + $(this).find("link").text() + '"></a>'
                                             ^-- add this guy here 

3). One more thing: your selector must be $(".container") since container is a class, not id.

4). And finally there is one more little detail about how you should retrieve dc:creator node. Since this node is namespaced you need to escape it like this:

.find("dc\\:creator")

However it still doesn't guarantee that it will work in all browsers. You probably should do something like this:

$(this).find('dc\\:creator, creator').eq(0)

You provide two selectors here. The second selector creator will work in Chrome, and the first (escaped) in Firefox.

5). Also just in case, doccument is a probably a typo, but anyway it should be document .

Demo: http://plnkr.co/edit/0Z2tJJ3JANtJq30CNUDD?p=preview

您在$(doccument).ready写了doccument而不是document

The key to your problem is " I am using a local xml file ..." . If you look at your console I am pretty sure that you are getting an "Access-Control-Allow-Origin error". This is a browser model security problem. Have a read here if you need more info.

In short though Access-Control-Allow-Origin errors occurs when you call a Web Service such as do a GET request for an XML file, from a domain that is different from the one hosting your HTML page. In you case I believe that you are your HTML file is on your hard drive while the Web Service is called on the localhost.

For development purposes you can use this chrome plugin . That will work for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM