Reputation: 79
I am trying to make an jQuery ajax request to AWS S3 to list bucket objects. Since AWS only wants to respond with XML, I am having trouble using (or going around) the data type JSONP.
$.ajax({
method: 'GET',
url: "http://BUCKET.s3.amazonaws.com/?querystring", // returns xml
dataType: 'jsonp',
// dataType: 'jsonp xml',
success: function(data) {
console.log('success', data);
},
error: function(err) {
console.log('err', err);
}
}).done(function(data) {
console.log('finished', data);
});
Gives error Uncaught SyntaxError: Unexpected token <
because it is receiving XML instead of JSON.
I understand that cross domain requests are blocked by default, so I'd normally use JSONP. However that gives me a syntax error when returning xml, and I'm not sure how to convert from xml to json before that point. In the ajax request I tried converting dataType with "jsonp xml", but really don't I want to be doing xml->json? Which gives an error as it is expecting json first.
I've checked out these other questions but am still having trouble, any help would be greatly appreciated.
edit: also this is a static html site.
How to Parse XML Cross-domain in jQuery?
Upvotes: 1
Views: 1749
Reputation: 6678
Cross-domain in AJAX is only enabled for JSON but if you need XML to parse on cross-domain, you have one trick.
You can create one PHP file on your server and store in that file XML parser class.
EXAMPLE OF PHP CODE:
function simplexml_load_file_curl($url) {
$xml="";
if(in_array('curl', get_loaded_extensions())){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$xml = simplexml_load_string(curl_exec($ch));
curl_close($ch);
}
else{
$xml = simplexml_load_file($url);
}
return $xml;
}
$xml = simplexml_load_file_curl('http://example.org/xml-file-url.xml');
After that point your AJAX to that PHP file and get your data. With that, you are able in PHP file to convert XML into JSON and use JSON objects in your javascript for other works OR just return XML data in AJAX and use that.
You are the master of your data from there.
Upvotes: 2