I need a java script function that converts the document object of the current loaded page back to it's source text. In firefox it's smth like that:
var doc = document;
var str = (new XMLSerializer()).serializeToString(doc);
alert(str);
But i need a cross browser solution. How would this be done?
For example:
<html>
<body>
<script>
alert( asText(document) );
</script>
</body>
</html>
would pop up:
<html>
<body>
<script>
alert( asText(document) );
</script>
</html>
how would you implement the 'asText' function?
Why do not you use document.documentElement.innerHTML?
example
function sourceText(){
try{
var O= new XMLHttpRequest();
O.open('GET', location.pathname, false);
O.send(null);
return O.responseText;
}
catch(er){
return '';
}
}
Related
I have the following script in my HTML, however I get a Question mark instead of the actual IP:
<script type="application/javascript">
var myButton = document.getElementById("clickButton");
var myText = document.getElementById("helloText");
myButton.addEventListener('click A', doSomething(), false);
function doSomething(json) {
myText.textContent = (json.ip);
}
function getIP(json) {
return json.ip;
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP">
</script>
The problem is that doSomething doesn't receive the JSON as an argument. You need getIP to put the returned IP into a global variable, and then doSomething can display it.
var myButton = document.getElementById("clickButton");
var myText = document.getElementById("helloText");
myButton.addEventListener('click', doSomething, false);
function doSomething() {
myText.textContent = IP;
}
<script type="application/javascript">
var IP;
function getIP(json) {
IP = json.ip;
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP">
</script>
<button id="clickButton">Show IP</button>
<div id="helloText"></div>
Also, the second argument to addEventListener should just be the function name, not a call to the function. And the first argument should just be the name of the event. There's no click A event, just click.
The function getIP() gets called when the //api.ipify.org script is loaded. Your getIP() function just returns the ip address. Other than that it does not do anything. Try doing something like this:
<div id="mydiv"></div>
<script>
var getIP = function(json) {
document.getElementById("mydiv").innerHTML = json.ip;
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP">
</script>
First thing I am new to javascript.
What I am trying to do is to get data from a URL in json and save it in java script variable.
What I have already done:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
This shows me output : 1
and what I want is to get data from URL like:
var json ='url';
obj = JSON.parse(json);
alert(obj.count);
and for the clearance I am using this URL to get JSON data and i just need to print fare from the data.
any help in this matter would be highly appreciated !!
I have done this in php like this way, but I need it to do this in javascript.
$jsonData = file_get_contents("url");
$json = json_decode($jsonData,true);
echo $json['fare'];
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
console.log(data)
});
Try this ways to read ur URL
Try this way, convert the url to an array then
var json = 'data url in array',
obj = JSON.stringify(json);
alert(obj.count);
Use Ajax call for fetching data from external sources.
On clicking it will fetch data from the url.
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://daewoocab-test.herokuapp.com/api/v1/rates?token=6ab676ddd7bf00101408ea3a27fdbb8ad22e9dcdf2faafdcd2ef0efc1509d463&pickup_area=Street%201%2CF-8%2CIslamabad%2CIslamabad%20Capital%20Territory%2CPakistan&drop_area=padhrarazadari.com%2C%20kallar%20kahar%20road%2C%20padhrar%2C%20punjab%2C%20pakistan&distance=169", function(result){
console.log(result);
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<button onclick="showHint()">abcd</button>
<script>
function showHint() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(JSON.parse(xhttp.response));
}
};
xhttp.open("GET", "http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback", true);
xhttp.send();
}
</script>
</body>
</html>
Temporary Solution:
Here is my working fiddle
If you get 'Access-Control-Allow-Origin' header is present on the requested resource. error, add CORS extension to your browser and enable it.
hope this helps :)
I'm a new programmer that learn javascript, Im new in js actually.
I have a task that require a web page able to read file in client directory. I've got some js code :
<html>
<script type="text/javascript">
function ReadWeight() {
var filePath = "file:///D:/Text.txt";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",filePath,false);
xmlhttp.send(null);
var fileContent = xmlhttp.responseText;
alert(fileContent);
}
ReadWeight();
</script>
<body>
</body>
</html>
When I save this code in my directory and access it by this link, It works well.
file:///D:/test.html
But when I put it in my localhost and I access it, the JS doesn't works.
Does my code incorrect when in web server?
Please help me out.
Might I suggest using an error console to display the error so people know how to help you? =] And paste it in your query
Download something like firebug and see if a request is being made (for FireFox)
It looks like you would rather want to access the file via the http:// protocol, instead of file://
As far as I know you can only read client files using an <input type="file"> element. Once you get the file you can read it multiple times:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Refresh</title>
<script src="filerefresh.js"></script>
</head>
<body>
<input id="fileInput" type="file">
<pre id="fileDisplay"></pre>
</body>
</html>
JavaScript:
(function() {
var sleepInterval = 1000; // 1 second
var fileInput;
var fileDisplay;
var reader;
var id = undefined;
function initialize() {
fileInput = document.getElementById("fileInput");
fileDisplay = document.getElementById("fileDisplay");
reader = new FileReader();
reader.onloadend = function() {
fileDisplay.innerHTML = reader.result;
reschedule();
};
fileInput.addEventListener("change", readFile);
}
function reschedule() {
if (id !== undefined) {
clearTimeout(id);
}
id = setTimeout(readFile, sleepInterval);
}
function readFile() {
reader.readAsText(fileInput.files[0]);
}
window.onload = initialize;
})();
Here is some script I copied to create a mailto link which grabs the browser URL and inserts it into the subject of the email. Its working perfect but every page I go to a Javascript alert box pops up saying:
mailto:address#address.ca?Subject="WHAT EVER IS IN THE BROWSER ADDRESS BAR"
Im rubbish with JS. How do I get the script to work without the alert pop up or even so with a lifespan?
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'>
</script>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function(){
var url = "mailto:address#address.ca?Subject=" + window.location;
$('#mailtoLink').attr('href', url);
window.alert($('#mailtoLink').attr('href')); // = url;
});//]]>
</script>
HERE IS A EXAMPLE PAGE:
http://www.door9.co.uk/bex/his-thoughts/
Just remove this line window.alert($('#mailtoLink').attr('href')); // = url; so you're left with:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'>
</script>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function(){
var url = "mailto:address#address.ca?Subject=" + window.location;
$('#mailtoLink').attr('href', url);
});//]]>
</script>
Just remove the window.alert function call.
https://developer.mozilla.org/en-US/docs/DOM/window.alert
Take out this line; it was clearly for demo purposes only
window.alert($('#mailtoLink').attr('href')); // = url;
I have a graph library that I use to plot some data.
This data comes passed as a GET paramater in the URL in the following format: plottedgraph.html?case_id=4&otherparam=blabla
Then I have my HTML page where I try to catch that GET param with the GUP function (below) and add it to my JS function as follows: "http://www.url.com/showgraph.do?case_id=" + gup('case_id') + "&status=weighted"
This is the whole HTML
<html>
<head>
<!--[if IE]>
<script type="text/javascript" src="js/excanvas.js"></script>
<![endif]-->
<script type="text/javascript" src="js/dygraph-combined.js"></script>
<script type="javascript">
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
</script>
</head>
<body>
<div id="graphdiv2" style="width:1800; height:900px;"></div>
<script type="text/javascript">
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"http://www.url.com/showgraph.do?case_id=" + gup('case_id') + "&status=weighted", // path to CSV file
{
showRoller: true,
colors: ["rgb(255,100,100)",
"rgb(72,61,139)"]
} // options
);
</script>
</body>
</html>
Unfortunately the JS function doesn't recognize that case_id=4 in this case...
Could you please let me know what am I doing wrong?
It's a bit hard to debug you gup() function, could you try:
var params={};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
params[decode(arguments[1])] = decode(arguments[2]);
});
You can now find your parameters in the params object, so params['case_id'] will hold the value you're looking for.