问题
I have a website where I'd like to make a request to the BBC RSS feed to return the latest news. The problem is I get the following error:
Uncaught SyntaxError: Unexpected token <
This is my code:
var url = 'http://feeds.bbci.co.uk/news/rss.xml';
$.ajax({
url : url,
dataType : 'jsonp',
contentType : 'text/xml',
success : function(data) {
console.log(data);
}
});
Edit
Here is my code on my server, as suggested by the answers below:
public XmlDocument callBBCFeed()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://feeds.bbci.co.uk/news/rss.xml");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string result = sr.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(result);
return doc;
}
I then call this in my JS code like so:
var url = 'http://myServer/Global/callBBCFeed';
$.ajax({
url : url,
dataType : 'xml',
success : function(data) {
console.log(data);
}
});
But I get the Same Origin Policy Error
回答1:
Check your $.ajax call: dataType: 'jsonp'
.
RSS is XML. Since your call expects retrieving JSON, <
is an ilegal character, isn't it?
Read jQuery $.ajax documentation and look for "dataType" option:
- http://api.jquery.com/jQuery.ajax/
UPDATE
Based on some comment that you added to some other answer, it seems that your initial problem is cross-domain requesting.
Best solution for that is do that cross-domain call from the server-side (using server code in ASP.NET C#/VB or whatever, PHP, Perl, Ruby...) and jQuery will call your server handler to retrieve that RSS feed, so it's not a cross-domain request anymore.
回答2:
You are sending a cross domain AJAX request to an XML resource. That cannot work due to the same origin policy restriction.
You are in a complete contradiction here:
dataType : 'jsonp'
and yet sending a request to a XML resource.
JSONP which allows for cross domain AJAX calls is something entirely different. It represents a JSON response wrapped in a javascript function that might look like this:
someFunctionName({"foo":"bar", "baz":"bazzy"})
If the remote server doesn't support JSONP, you will have to write a server side script on your domain that will serve as a bridge between yours and the remote domain to fetch the XML file. Then use jQuery AJAX to send a request to your script.
I would recommend you reading the following jQuery cross domain AJAX guide for different techniques that could be used.
来源:https://stackoverflow.com/questions/11340020/returning-xml-from-an-ajax-requestfor-rss-feed