Wordpress json - How to use the content rendered from json - json

Using basic Wordpress basic Json in the format //domain.com/wp-json/wp/v2/pages/ I can access to a specific page content.
What I need to do is to use the rendered content as html of a blank page.
How to store this content into a variable so that I can use it? I suppose I shloud store into an array. Any sample?
Thank you.

How to store this content into a variable so that I can use it?
var x = data.content.rendered;
Where data is the JSON object you provided.
After this line is executed, x will contain HTML that you can use it in your project.
What I need to do is to use the rendered content as html of a blank page.
Any sample?
//change this values
var wpApiBaseURL = "http://localhost/wp-json/wp/v2/";
var pageId = 2; // id of the page to fetch
//
var container = document.getElementById("container");
// fetch specific page
fetch(wpApiBaseURL + "pages/" + pageId)
.then(function(rawResponse) {
return rawResponse.json();
})
.then(function(jsonResponse) {
// load successful and replaces html contents of the container div
container.innerHTML = jsonResponse.content.rendered;
})
.catch(function(error) {
container.innerText = "Error loading page";
});;
<!DOCTYPE html>
<body>
<div id="container">
Loading
</div>
</body>

Related

How to get clean json from wikipedia API

I want to get the result from a wikipedia page https://en.wikipedia.org/wiki/February_2 as JSON.
I tried using their API: https://en.wikipedia.org/w/api.php?action=parse&page=February_19&prop=text&formatversion=2&format=json
Though it is giving it as Json format. The content is HTML. I want only the content.
I need a way to get clean result.
If you want plain text without markup, you have first to parse the JSON object and then extract the text from the HTML code:
function htmlToText(html) {
let tempDiv = document.createElement("div");
tempDiv.innerHTML = html;
return tempDiv.textContent || tempDiv.innerText || "";
}
const url = 'https://en.wikipedia.org/w/api.php?action=parse&page=February_19&prop=text&format=json&formatversion=2&origin=*';
$.getJSON(url, function(data) {
const html = data['parse']['text'];
const plainText = htmlToText(html);
const array = [...plainText.matchAll(/^\d{4} *–.*/gm)].map(x=>x[0]);
console.log(array);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Update: I edited the code above according to the comment below. Now the function extracts all the list items putting them into an array.
I guess by clean you mean the source wikitext. In that case you can use the revisions module:
https://en.wikipedia.org/w/api.php?action=query&titles=February_2&prop=revisions&rvprop=content&formatversion=2&format=json
See API:Get the contents of a page and API:Revisions for more info.

HTML script to convert a text string(s) into a specified hyperlink

My basic requirement is to convert given text anchors into hyperlinks, using HTML or any browser side script. We use Windows10/IE/Edge, FYI.
Example : Given text
ABC
CDE
EFG
Required Output:
www.xyz.com/test/ABC
www.xyz.com/test/CDE
www.xyz.com/test/EFG
I have found a bash to hyperlink query here. My requirement is similar but need a browser based script
How to create html links based on a text document of inputs
Put text in <textarea> and read it's content using js/jQuery.
Create links dynamically in memory and later use where needed (I simply append to DOM)
var urlBase = 'https://example.com';
$(document).ready(function () {
$('#input').change(function () {
var lines = $(this).val().split("\n"); // Split textarea content by new line
var links = $('#links'); // Links container
links.html(''); // Empty container content
$.each(lines, function (i, line) {
links.append($('<a>', {href: urlBase + '/' + line, text: line})); // Append new link element
})
})
})
#links a {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="input"></textarea>
<div id="links"></div>
Get the value of the text input, split it at the new lines and create a string of the a's with teh desired hrefs. I am using a ul to display the results.
Note the advantage of creating a string that is then added to the DOM is that it affects the DOM only once - rather than on each loop of the append option. A small matter for when there is a small list, but if there are millions of lines to be appended - the constant DOM maniulation may cause issues if you use .append().
function convertText(){
var links= document.getElementById('textInput').value;
var linksArr = links.split('\n');
var linkStr = '';
linksArr.forEach(function(link){
linkStr += '<li>'+link+'</li>';
})
document.getElementById('results').innerHTML = linkStr;
}
<textarea id="textInput"></textarea>
<hr/>
<button type="button" onclick="convertText()">Convert text to links</button>
<ul id="results"></ul>

Displaying data of Firebase into simple HTML page

I was wondering how I could display multiple rows of data in Firebase onto a blank page/simple website.
I am currently using this to display a simple string:"Testing" through this method:
var bigOne = document.getElementById('bigOne');
var dbRef = firebase.database().ref().child('text');
dbRef.on('value', snap => bigOne.innerText = snap.val());
How it looks in Firebase
How it looks on a blank site
But how can I display multiple lines/rows of data from Firebase onto the blank page?
With multiple lines/rows of data I mean this:
Firebase data
EDIT: This is my current code: Image
However it shows nothing on my HTML page. Do I have to add this line of code back or adjust it? If I add it back it says: [object Object] on the site.
dbRef.on('value', snap => bigOne.innerText = snap.val());
You should listen to a list of items and loop over the items:
First you should adapt your dbRef to
var dbRef = firebase.database().ref('sensor/dht');
then query as follow
var tempo = '';
dbRef.on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
tempo += 'temp: ' + childSnapshot.val().temp + ' - humidity: ' + childSnapshot.val().humidity + '<br>'; //Just an example of formatting the output
});
bigOne.innerText = tempo;
});
Have a look a the doc at https://firebase.google.com/docs/database/web/lists-of-data#reading_and_writing_lists

How would you use rivets.js with HTML template tags

HTML has a draft specification for a < template > tag. Details here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template
I'm thinking about using Rivets.JS on a new project, I also want to use this new template tag.
Can the two be made to work together nicely?
I imagine I'd want to tell rivets something along the lines of 'get this template, bind it to this data and output the result here'.
You can copy the template as your normally would, and then use Rivets to bind to your new element. demo # jsfiddle
HTML:
<template id="demo">
<p id="tag">{ demo.info }<p>
</template>
Javascript:
var demo = {
info: "Test string"
}
// Copy template data to visible DOM
var el = document.getElementById("demo");
var clone = document.importNode(el.content, true);
document.body.appendChild(clone);
// Bind using Rivets as normal
var tag = document.getElementById("tag");
rivets.bind(tag, { demo: demo });

Extract the contents of a div using Flash AS3

I have a SFW embedded in a PHP page. There is also a div on the page with id="target".
I want to access the content of that div (ie: the characters inside it) and hold them as a String variable in AS3. How can I do this?
My attempt so far
import flash.external.ExternalInterface;
var myDivContent = ExternalInterface.call("function(){ return document.GetElementById('target');}");
var myDivContent2:String = myDivContent.toString();
test_vars.text = myDivContent2; //Dynamic text output
I don't think you can define a function in the ExternalInterface.call() method. You have to call a function by name which already exists in the JavaScript.
So I'd create some JavaScript code like this:
function getTargetContent()
{
return document.getElementById('target').innerHTML;
}
And then in your Flash,
var myDivContent = ExternalInterface.call("getTargetContent");
Note that document.getElementById('target') only returns the reference to that div, not the contents within. So if you don't return .innerHTML then the Flash will get an object which may not be usable (although I haven't actually tried doing this).
The easiest way to do this is as Allan describes, write a Javascript function to sit on the page and return the required value to you.
Of course, if you can't edit the page content, only the flash, then you do need to pass the function itself, which will actually have to be forced into the page though JavaScript injection. An example for your case, which I have not tested:
//prepare the JavaSctipt as an XML object for Dom insertion
var injectCode:XML =
<script>
<![CDATA[
function() {
getElementContent = function(elementID) {
return document.getElementById(elementID).innerHTML;
}
}
]]>
</script>;
//inject code
ExternalInterface.call(injectCode);
//get contents of 'divA'
var divAContent:String = ExternalInterface.call('getElementContent','divA') as String;
//get contents of 'spanB'
var spanBContent:String = ExternalInterface.call('getElementContent','spanB') as String;
You're almost there :
var res : String = ExternalInterface.call("function(){return document.getElementById('target').outerHTML}");
If you only want the content of your target, use innerHTML instead of outerHTML.