JSON + jQuery not working - javascript

I'm trying to make jQuery take JSON file and put the data from it on a simple site, when a button is pressed.
So, the JSON code looks like this:
{
"images" : [
{ "source" = "images1", "alternative" = "altImg1" },
{ "source" = "images2", "alternative" = "altImg2" },
{ "source" = "images3", "alternative" = "altImg3" }
]
}
And the HTML + jQuery:
<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<title>jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<button>Press Me!</button>
<script>
$('button').click(function() {
$.getJSON('json-db.html', function(data) {
for(var i = 0; i < data.images.length; i++) {
var image = data.images[i];
$('#result').append('<h1>' + image.source + ' ' + image.alternative + '</h1>');
}
});
});
</script>
<div id="result">Result</div>
</body>
</html>
There are no errors detected by Firebug. I rewrote the code several times, looked for mistakes, compared it to a similar code and so on, but couldn't find anything.
Thanks in advance!

your json notation is wrong
use : instead of = like:
..........
"images" : [
{ "source" : "images1", "alternative" : "altImg1" },
....................
]
..........

Related

Extract a variable value in JavaScript code from HTML

I'm getting the HTML code of a webpage using this parsing library called Kanna. Basically the stripped down version looks like this.
<!DOCTYPE html>
<html lang="en" class="no-js not-logged-in client-root">
<head>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript">
window._sharedData = {
// Some JSON
};
</script>
<script type="text/javascript">
// Javascript code
</script>
<script type="text/javascript">
// More Javascript code
</script>
</body>
</html>
There are multiple script tags within the body. I want to access the one with the variable named window._sharedData and extract it's value which is a JSON dictionary.
I tried with using regular expressions but it's returning nil. Maybe something's wrong with my pattern?
if let doc = try? HTML(url: mixURL, encoding: .utf8), let body = doc.body, let htmlText = body.text {
let range = NSRange(location: 0, length: htmlText.utf8.count)
let regex = try! NSRegularExpression(pattern: "/<script type=\"text/javascript\">window._sharedData = (.*)</script>/")
let s = regex.firstMatch(in: htmlText, options: [], range: range)
print(s)
}
Or is there a better way to do this?
Here it is:
import Foundation
import Kanna
let htmlString = "<!DOCTYPE html><html lang=\"en\" class=\"no-js not-logged-in client-root\"><head> <meta charset=\"utf-8\"></head><body> <script type=\"text/javascript\"> window._sharedData = { \"string\": \"Hello World\" }; </script> <script type=\"text/javascript\"> </script> <script type=\"text/javascript\"> </script></body></html>"
guard let doc = try? HTML(html: htmlString, encoding: .utf8) else { print("Build DOM error"); exit(0) }
let body = doc.xpath("//script")
.compactMap { $0.text }
.filter { $0.contains("window._sharedData") }
.map { $0.replacingOccurrences(of: " window._sharedData = ", with: "") }
.map { $0.dropLast(2) }
.first
print("body: ", body)
// body: Optional("{ \"string\": \"Hello World\" }")
After that you can check that body not nil and ready

why javascript doesnt run

I am learning JavaScript.
I've written this code, but it does not seem to run.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<script language="javascript" type="text/javascript">
function nav(){
try{
var str="<table border=1>";
for (var n in navigator){
str+="<tr><td>" + n + "</td></tr>";
}
str+="</table>
return("jetzt wird das Ding aufgelistet: <br/>" + str);
}catch(e){return(e);}
}
function writeit(){
document.write(nav());
}
</script>
<title>for learning purpos</title>
</head>
<body>
<form>
<script>
document.write(nav());
</script>
<p>press the button to get the properties in navigator</p>
<input type="button" id="btnNavigator" value="get" onclick="writeit();"/>
</form>
</body>
</html>
You haven't closed one string.
str+="</table>";
Best practice is to look into the console from developer tab, inspect page. Also on that tab on the bottom, you can try javascript code or even jQuery if you have the library added.
Your code it's wrong at line 13 you have Invalid or unexpected token because you didn't close the string and at line 30 nav it's not defined.
You can use this code:
function navBuild(n)
{
var tblS = "<table>";
var tblE = "</table>";
var strTrTd = "";
for (i=1; i<=n; i++)
{
strTrTd = strTrTd + "<tr><td>" + i + "</td></tr>";
}
var strAll = tblS + strTrTd + tblE;
console.log(strAll);
document.getElementById("contentBox").innerHTML = strAll;
}
And in your HTML you could use:
<input type="button" id="btnNavigator" value="get" onclick="navBuild(5);"/>
<div id="contentBox"></div>

dynamically created td change onclick

I have a a table which has dynamic td's i want to change the weight of letters when clicked. following is my coding but it changes the whole page when clicked. Please tell me where I got it wrong.
function addHandler()
{
var addH=document.getElementsByTagName('td');
for( var i=0;i < addH.length;i++)
{
if(addH[i].addEventListener)
{
addH[i].addEventListener('click',addBold,false);
}
else if(addH[i].attachEvent)
{
addH[i].attachEvent('onclick',addBold);
}
}
}
function addBold()
{
var add=document.getElementsByTagName('td');
for( var i=0;i < add.length;i++)
{
var weightVal=add[i].style.fontWeight;
if(weightVal!=900)
{
add[i].style.fontWeight="900";
}
else
{
add[i].style.fontWeight="100";
}
}
}
Your addBold routine is setting ALL td's. The following works. I wish I could give you a reference link, but I can't. I want that link myself.
[edit] This page works like I think you want it to. Does it work for you?
The "e" gets passed to the event handler. I wish I could say more.
Like I said, I'm looking for a reference on how this works. But it does.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style type="text/css">
</style>
<script type="text/javascript">
function addHandler() {
var addH=document.getElementsByTagName('td');
for( var i=0;i < addH.length;i++) {
if(addH[i].addEventListener) {
addH[i].addEventListener('click',addBold,false); }
else if(addH[i].attachEvent) {
addH[i].attachEvent('onclick',addBold); } }
}
function addBold(e) {
if (e.target.style.fontWeight != "900") {
e.target.style.fontWeight = "900"; }
else {
e.target.style.fontWeight = "100"; }
}
</script>
</head>
<body onload="addHandler();">
<div id="bodyid">
<table border="1">
<tr><td>One1</td><td>Two1</td></tr>
<tr><td>One2</td><td>Two2</td></tr>
</table>
</div><!-- bodyid -->
</body>
</html>

jQuery - Detect change in Boolean value

Is there a way to detect if an global Boolean values changes from false to true with jQuery?
Yes, use a getter/setter pair of which the setter traps the setting of the variable: http://jsfiddle.net/M768B/.
(function() {
var val = false;
​Object.defineProperty(window, "something", {
get: function() {
return val;
},
set: function(v) {
val = !!v; // `!!` to force setting a boolean
alert("Changed to " + val);
}​​
});
})();
Keep an array of function callbacks as "observers". When anything changes the Boolean through your interface function (e.g. setBooleanValue(True); ) then iterate through the callback array and call each function to notify the observers.
The solution might be
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript Object - watch () method example</title>
</head>
<body>
<h1 style="color: red">JavaScript Object : watch() method</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[ o = {x:10}
o.watch("x",
function (id,oldvalue,newvalue) {
document.writeln("o." + id + " changed from "
+ oldvalue + " to " + newvalue+"<br />")
return newvalue
})
o.x = 20
o.x = 30
o.x = 40
//]]>
</script>
</body>
</html>
Compatible with:
Internet Explorer 7
Firefox 3.6
Google Chrome 7
Safari 5.0.1
Opera 10
Seen here.

Why is this JavaScript code not working?

Why is this code working? I want to take the input variable and getting the emails out of it. It's not working though. Can someone help me?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var email = /[a-z0-9\.&%]+#(?:[a-z1-9\-]+\.)+[a-z]{2,4}/i;
var input = "hi4d#gmail.com#gmail.com text here shaagd4##fdfdg.ct hefds#4564dh-dsdgd.ly";
var testout = true;
var output;
while(testout === true)
{
var execoutput = email.exec(input);
testout = email.test(input);
if(!output) {output = '';}
if(testout === true)
{
output += "<p>An email found was: " + execoutput[0] + ".</p>";
input = input.substring(execoutput[0].length);
}
}
document.write(output);
</script>
</head>
<body>
</body>
</html>
Try this: (on jsfiddle)
var email = /[a-z0-9\.&%]+#(?:[a-z0-9\-]+\.)+[a-z]{2,4}/i;
var input = "hi4d#gmail.com#gmail.com text here shaagd4##fdfdg.ct hefds#4564dh-dsdgd.ly";
var output = '';
for (;;) {
var execoutput = email.exec(input);
if (!execoutput) {
break;
}
output += "<p>An email found was: " + execoutput[0] + ".</p>";
input = input.substring(execoutput.index + execoutput[0].length);
}
document.write(output);
Note a few problems I've corrected:
The regex did not match the 0 character in the domain part. None of your input strings contained this character in the domain part, but it was a bug nonetheless.
You can't just pull off the first N characters of the input string when N is the length of the matched string, because it may not have matched at position 0. You have to add the index of the match too, or you might match the same address multiple times.
As mentioned in the comment, the code works.
It should however be duly noted I just slapped your code straight into my current project (Yay for messing up stuff!) and it works just fine there too.
HOWEVER it does not LOOK right, nor provide the correct output I suspect you want.

Categories

Resources