I'm trying to use Mozilla Readability stand-alone library for a personal project I am currently developing. The idea is to pass Mozilla Readability a document element and that after some parsing magic it returns the document's title, author, text, etc.
So, the first thing is dealing with how to get the HTML source of an external URL. I have dealt with that using an internal PHP file, which retrieves this external URL's source code.
After that, I call an AJAX GET to process the data returned by my PHP file. However, I am having lots of problems to convert this HTML source into an actual Javascript document element to pass to Mozilla Readability.
This is the code that I am currently using:
$('#btn_fetch').on('click', function() {
var url = 'https://www.rtl.be/info/monde/france/pierre-bellemare-s-est-eteint-a-88-ans-1025563.aspx';
$.ajax({
type: "GET",
url: 'fetchurl.php',
data: {
url: url
},
dataType: "html"
})
.done(function(data) {
var doc = document.implementation.createHTMLDocument("New Document");
// i don't know how to add "data" into "doc" element !
var article = new Readability(doc).parse();
alert(article.title);
})
.fail(function(xhr, ajaxOptions, thrownError) {
alert('Error:' . thrownError);
});
});
I just discovered it was actually very easy. The line I was missing was...
doc.body.parentElement.innerHTML = data;
it should be added here in the .done function
.done(function(data) {
var doc = document.implementation.createHTMLDocument("New Document");
// you need to add it here
doc.body.parentElement.innerHTML = data;
var article = new Readability(doc).parse();
alert(article.title);
})
Related
I'm currently working on a website which should heavily rely on ajax. But I'm facing a problem which I cannot find a solution to online.
I'll now shamelessly post my (stripped) function to completely fetch a page.
function loadTemplate(name, replaceWholePage = true){
$.when( $.ajax({ url: "./templates/{0}/{0}.html".format(name), error: function() { console.error( "Could not load HTML file of template '{0}'!".format(name)); }}),
$.ajax({ url: "./templates/{0}/{0}.css".format(name), error: function() { console.error("Could not load CSS file of template '{0}'!".format(name)); }}),
$.ajax({ url: "./templates/{0}/{0}.js".format(name), error: function() { console.error("Could not load JS file of template '{0}'!".format(name)); }}) )
.then(function(html, css, js) {
var _css = "\n<style>\n" + css[0] + "\n</style>";
var _js = "\n<script>\n" + js[0] + "\n</script>";
if(replaceWholePage) {
$("#content").empty();
}
$("#content").append(html[0]);
$("#content").append(_css);
//$("#content").append(_js);
});
}
You see the line where it appends the js file is commented. But somehow the site still gets the js. When I comment that line out, my js code isn't actually twice in the document, but still gets called twice.
As Varinder stated, jQuery automatically recognised the fetched file as javascript and executed it. Setting the dataType to "text" in the call fixed it!
Thanks
I am trying to load an xml file containing config for a single page apps logic using jquery.
I can get the console to show the xml has been loaded and even display the xml in console but have yet to be able to get the xml to be declared as a string variable. I am using the following code
$.ajax({
type: "GET",
url: "dummy.xml",
dataType: "xml",
success: function (url) {
console.log('started function xml');
console.log(url);
// Parse the xml file and get data
parseXMLConfig;
}
});
I have a separate function to parse the xml using jquery which works if I declare the xml directly in the JavaScript but need to separate the xml and js for later development efforts.
Can anyone tell me how to set the js object to a variable for use elsewhere in scripts.
You can do something like this
$.ajax({
type: "GET",
url: "dummy.xml",
success: function (xmContent) {
console.log(xmContent);
xmlDoc = $.parseXML(xmContent),
$xml = $( xmlDoc ),
$title = $xml.find( "title" );
console.log($title );
}
});
For more detail refer DOC
I am trying to get a list of a user's Jive SBS permission groups. How would this be done with jQuery?
Using the Jive v3 API this isn't so hard. The worst part is that you have to sanitize the result from Jive to make it valid JSON. Thankfully you can use Datafilter.
// We will use this as our data filter in the AJAX call
sanitizeJiveJsonResponse: function(response){
return response.replace("throw 'allowIllegalResourceCall is false.';", '');
},
// You can get the logged in user id from the __jive variable. Including any sort
// of JS in a Jive widget or tile will cause that code to run from an iframe, so
// we're using window.parent to reference it
var userid = window.parent._jive_current_user.ID;
if(typeof userid == 'undefined'){
// Error stuff here
}
$.ajax({
url: '/api/core/v3/people/' + userid + '/securityGroups',
context: document.body,
dataType: 'json',
dataFilter: function (data, type) {
return sanitizeJiveJsonResponse(data);
}
}).done(function(result) {
// Your success code here...
});
};
Hope this helps!
I want take some data from server and write it to global array in JavaScript. Then in document ready I want to use this array to create some new elements (options). I should have global array with this data, because after first load client can modify user interface using this data.
$(document).ready(function () {
UseAjaxQueryForFillGlobalArray();
MakingInterfaceUsingGlobalArray();
});
But I have strange behavior, when I debug page, I can see that method MakingInterfaceUsingGlobalArray working first, and just after I get data via AJAX with method UseAjaxQueryForFillGlobalArray and I don't have new interface(html options) with loaded data.
If I do like this:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
Then in Firefox working fine, but in another web-browsers incorrect in first load (for example go to this page by link). But if I refreshing by F5, I have correct user interface which loaded via AJAX to global JS array.
How to fix it? Maybe I using totally incorrect way?
Added after comments:
This is my ajax function:
function UseAjaxQueryForFillGlobalArray(){
var curUserId = '<%= Master.CurrentUserDetails.Id %>';
var curLocale = '<%= Master.CurrentLocale %>';
$.ajax({
type: "POST",
url: "/segment.aspx/GetArrayForCF",
data: '{"userId":"' + curUserId + '","curLocale":"' + curLocale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//here is I doing parse my string from server and fill arrays.
}
});
}
I think that the problem is that you don't know exactly when the first function returns, since it'a asynchronous. So you should use the array in the callback only
function UseAjaxQueryForFillGlobalArray() {
// make the call
$.post(url, data, function() {
// let's be sure that the dom is ready
$(document).ready(function () {
// use the array
MakingInterfaceUsingGlobalArray();
}
}
}();// invoke the function
It's like reviving this post from the dead, but I had the same problem today, jQuery version greater than 1.6 has this ability:
https://api.jquery.com/jquery.holdready/
And I've used it like this:
$.holdReady(true);
var remoteJSONContent = null;
$.getJSON("http://www.example.com/remote.json", function(data) {
remoteJSONContent = data;
$.holdReady(false);
});
$(document).ready(function(){
console.log(remoteJSONContent);
});
Without using holdReady, I was getting null, after, I got the content.
For anyone still searching the answer for this.
I found this site that allows to convert RSS feeds into json.
It also provides a way to specify a callback, so i think users are able to make jsonp calls to this web service.
However, i tried different ways to do that but none worked.
Here is my code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://www.blastcasta.com/feed-to-json.aspx',
dataType: "jsonp",
jsonpCallback: "loadRSS",
data: {
feedUrl: 'http://xml.corriereobjects.it/rss/homepage.xml',
param: "callback"
},
success: function (data) {
var list = "";
for (var propertyName in data) {
list+=data[propertyName];
}
console.log(list);
},
error: function(xhr, ajaxOptions, thrownError){
alert(ajaxOptions)
}
});
});
Whatever i try, the success handler doesn't get executed. I get error handler instead.
I tried with jsonpCallbak: "callback", jsonpCallback: "?", param: "callback" and other values too but without success.
I have to use ONLY javascript without the support any server side scripting language (no aps, no php, etc.)
Did someone get this service working in his site?
Any suggestion would be really appreciated!
I find jQuery JSON API not suitable for this kind of JSON response that provides BlastCasta service. It assigns JSON to a custom variable, specified in URL, and doesn't uses callback functionality JSONP operates with. For example this URL:
http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml¶m=rssFeed will return following response:
rssFeed = { "rss": { "channel": /*...*/}}
So, script injection technic may be used:
/* URL of the BlastCasta service and his parameters:
feedUrl :== escaped URL of interest (RSS Feed service)
param :== javascript variable name which will receive parsed JSON object */
var url = "http://www.blastcasta.com/feed-to-json.aspx"
+"?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml"
+"¶m=rssFeed";
/* since the service declares variable without var keyword,
hence in global scope, lets make variable usage via window object;
although you can write param=var%20rssFeed" in the URL :) */
window.rssFeed = null;
$.getScript(url, function() {
/* script is loaded, evaluated and variable is ready to use */
console.dir(window.rssFeed);
/* some feeds are huge, so free the memory */
window.rssFeed = null;
});
Update:
here's an example that works for your code:
$.getJSON("http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http://xml.corriereobjects.it/rss/homepage.xml¶m=?", function(data) {
console.dir(data);
});
problem is, that I get some javascript errors with returning json:
see this jsfiddle