Using jquery, How can I iterate every node in xml? - javascript

I have another question about below example code.
below is index.html file
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<style>
#frm, #raw {display:block; float:left; width:210px},
#raw {height:150px; width:310px; margin-left:0.5em}
</style>
<title> INDEX </title>
</head>
<body>
<form id="frm">
Profile: <select id="profiles">
<option> </option>
</select>
<br></br>
Format:<select id="formats">
<option value="json"> JSON </option>
<option value="xml"> XML </option>
</select>
<br></br>
<div id="output"></div>
</form>
<textarea id="raw"></textarea>
</body>
<script>
$.get("http://localhost:8080/profiles",function (profile_names) {
$.each(profile_names, function (i, pname) {
$("#profiles").append("<option>" + pname + "</option>");
});
}, "json");
$("#formats, #profiles").change(function () {
var format = $("#formats").val();
$.get("http://localhost:8080/profile/" + $("#profiles").val() + "." + format,
function (profile, stat, jqXHR) {
var cT = jqXHR.getResponseHeader("Content-Type");
$("#raw").val(profile);
$("#output").html('');
if (cT === "application/json") {
$.each($.parseJSON(profile), function (k, v) {
$("#output").append("<b>" + k + "</b> : " + v + "<br>");
});
return;
}
if (cT === "application/xml") {
xmlDoc = $.parseXML( profile ),
$xml = $( xmlDoc );
$($xml).each(function(){
$("#output").append($(this).text() + "<br/>");
});
}
},
"text");
});
</script>
</html>
Second, server.js file
var http = require('http');
var fs = require('fs');
var path = require('path');
var profiles = require('./profiles');
var xml2js = require('xml2js');
var index = fs.readFileSync('index.html');
var routes, mimes = {xml: "application/xml", json: "application/json"}
function output(content, format, rootNode) {
if (!format || format === 'json') {
return JSON.stringify(content);
}
if (format === 'xml') {
return (new xml2js.Builder({rootName: rootNode})).buildObject(content);
}
}
routes = {
'profiles': function (format) {
return output(Object.keys(profiles), format);
},
'/profile': function (format, basename) {
return output(profiles[basename], format, basename);
}
};
http.createServer(function (request, response) {
var dirname = path.dirname(request.url),
extname = path.extname(request.url),
// $.get('http://localhost:8080/profile/' + $('#profiles').val() + '.' + format
basename = path.basename(request.url, extname);
extname = extname.replace('.', ''); //remove period
response.setHeader("Content-Type", mimes[extname] ||'text/html');
if (routes.hasOwnProperty(dirname)) {
response.end(routes[dirname](extname, basename));
return;
}
if (routes.hasOwnProperty(basename)) {
response.end(routes[basename](extname));
return;
}
response.end(index);
}).listen(8080);
below is profiles.js file
module.exports = {
ryan: {
name: "Ryan Dahl",
irc: "ryah",
twitter: "ryah",
github: "ry",
location: "San Francisco, USA",
description: "Creator of node.js"
},
isaac: {
name: "Isaac Schlueter",
irc: "isaacs",
twitter: "izs",
github: "isaacs",
location: "San Francisco, USA",
description: "Former project gatekeeper, CTO npm, Inc."
}
};
at index.html file,
After if (cT === "application/xml") { is not working properly compare to JSON one.
Actually, the original example code was like this
if (cT === "application/xml") {
profile = jqXHR.responseXML.firstChild.childNodes;
$.each(profile, function (k, v) {
if (v && v.nodeType === 1) {
$("#output").append("<b>" + v.tagName + "</b> : " + v.textContent + "<br>");
}
});
but above one was not working so I searched a way to show all the child node and text at the
selected one.
Is there any way for XML to show the same format as JSON selected at index.html file?
Thank you for understanding dissy question!!!

I found the way exactly what I want to show for element name and text.
if (cT === "application/xml") {
var xmlDoc =$.parseXML( profile );
var $xml = $(xmlDoc);
var kids = $xml.children().children();
kids.each(function(){
var tagName=this.tagName;
var val=$(this).text();
$("#output").append("<b>" + tagName + "</b> : " + val + "<br>");
});
}
I do not know why but when profile is parsed for 'tj', below is the result.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tj>
<name>TJ Holowaychuk</name>
<irc>tjholowaychuk</irc>
<twitter>tjholowaychuk</twitter>
<github>visionmedia</github>
<location>Victoria, BC, Canada</location>
<description>Author of express, jade and many other modules</description>
</tj>
So first child of the $xml is <tj> </tj>. so I used children() method twice and then
I can iterate all of <tj> </tj>es child and then print child's name and text.
Is there someone who can explain my code clearly
Please let me know.
Thank you.

Related

How do I fix 401 error when using OMDB API?

EDIT: I have added the response from OMDB
{Response: "False", Error: "Invalid API key!"}
Error: "Invalid API key!"
Response: "False"
I am new to web development and I am trying to build a chrome extension that displays imdb scores on netflix. I am using the OMDB API to do this. At first I got the following error:
"Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint ''. This request has been blocked; the content must be served over HTTPS.",
however I just changed the "http" in the url to "https" and it went away. However, now I am getting a 401 error, which I think means my access is being denied.
This is a picture of the full error
Here is the code for the extension
Manifest file:
{
"manifest_version": 2,
"name": "1_ratings_netflix",
"version": "0.1",
"description": "Display imdb ratings on netflix",
"content_scripts": [
{
"matches": [
"https://www.netflix.com/*", "https://www.omdbapi.com/*"
],
"js": ["content.js"]
}
],
"icons": { "16": "icon16.png", "48":"icon48.png"},
"permissions": [
"https://www.netflix.com/*", "https://www.omdbapi.com/*"
]
}
Content File:
function fetchMovieNameYear() {
var synopsis = document.querySelectorAll('.jawBone .jawbone-title-link');
if (synopsis === null) {
return;
}
var logoElement = document.querySelectorAll('.jawBone .jawbone-title-link .title');
if (logoElement.length === 0)
return;
logoElement = logoElement[logoElement.length - 1];
var title = logoElement.textContent;
if (title === "")
title = logoElement.querySelector(".logo").getAttribute("alt");
var titleElement = document.querySelectorAll('.jawBone .jawbone-title-link .title .text').textContent;
var yearElement = document.querySelectorAll('.jawBone .jawbone-overview-info .meta .year');
if (yearElement.length === 0)
return;
var year = yearElement[yearElement.length - 1].textContent;
var divId = getDivId(title, year);
var divEl = document.getElementById(divId);
if (divEl && (divEl.offsetWidth || divEl.offsetHeight || divEl.getClientRects().length)) {
return;
}
var existingImdbRating = window.sessionStorage.getItem(title + ":" + year);
if ((existingImdbRating !== "undefined") && (existingImdbRating !== null)) {
addIMDBRating(existingImdbRating, title, year);
} else {
makeRequestAndAddRating(title, year)
}
};
function addIMDBRating(imdbMetaData, name, year) {
var divId = getDivId(name, year);
var divEl = document.getElementById(divId);
if (divEl && (divEl.offsetWidth || divEl.offsetHeight || divEl.getClientRects().length)) {
return;
}
var synopsises = document.querySelectorAll('.jawBone .synopsis');
if (synopsises.length) {
var synopsis = synopsises[synopsises.length - 1];
var div = document.createElement('div');
var imdbRatingPresent = imdbMetaData && (imdbMetaData !== 'undefined') && (imdbMetaData !== "N/A");
var imdbVoteCount = null;
var imdbRating = null;
var imdbId = null;
if (imdbRatingPresent) {
var imdbMetaDataArr = imdbMetaData.split(":");
imdbRating = imdbMetaDataArr[0];
imdbVoteCount = imdbMetaDataArr[1];
imdbId = imdbMetaDataArr[2];
}
var imdbHtml = 'IMDb rating : ' + (imdbRatingPresent ? imdbRating : "N/A") + (imdbVoteCount ? ", Vote Count : " + imdbVoteCount : "");
if (imdbId !== null) {
imdbHtml = "<a target='_blank' href='https://www.imdb.com/title/" + imdbId + "'>" + imdbHtml + "</a>";
}
div.innerHTML = imdbHtml;
div.className = 'imdbRating';
div.id = divId;
synopsis.parentNode.insertBefore(div, synopsis);
}
}
function getDivId(name, year) {
name = name.replace(/[^a-z0-9\s]/gi, '');
name = name.replace(/ /g, '');
return "aaa" + name + "_" + year;
}
function makeRequestAndAddRating(name, year) {
var url = "https://www.omdbapi.com/?i=tt3896198&apikey=**{API_KEY}**" + encodeURI(name)
+ "&y=" + year + "tomatoes=true";
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (xhr.status === 200) {
var apiResponse = JSON.parse(xhr.responseText);
var imdbRating = apiResponse["imdbRating"];
var imdbVoteCount = apiResponse["imdbVotes"];
var imdbId = apiResponse["imdbID"];
var imdbMetaData = imdbRating + ":" + imdbVoteCount + ":" + imdbId;
window.sessionStorage.setItem(name + ":" + year, imdbMetaData);
window.sessionStorage.setItem("metaScore:" + name + ":" + year, metaScore)
window.sessionStorage.setItem("rotten:" + name + ":" + year, rottenRating);
addIMDBRating(imdbMetaData, name, year);
addRottenRating(rottenRating, name, year);
addMetaScore(metaScore, name, year);
}
};
xhr.send();
}
if (window.sessionStorage !== "undefined") {
var target = document.body;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
window.setTimeout(fetchMovieNameYear, 5);
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(target, config);
}
It would be helpful for you to post the request and response for OMDB (you can find them in the "Network" tab in dev tools).
One thing that triggers CORS (cross-origin requests) errors is specifying a content type other than application/x-www-form-urlencoded, multipart/form-data or text/plain. If I recall correctly, the OMDB API will return a JSON response even without specifying the content type of the request, so you should try removing the line:
xhr.setRequestHeader('Content-Type', 'application/json');
More on "Simple Requests" which do not trigger CORS: https://javascript.info/fetch-crossorigin#simple-requests
You also need to get an API key (https://www.omdbapi.com/apikey.aspx) and replace
**{API_KEY}** in your code with the key. You also need to add the t key to your querystring or the title will be appended to your API key.
var url = "https://www.omdbapi.com/?i=tt3896198&apikey=**{API_KEY}**" + "&t="
+ encodeURI(name) + "&y=" + year + "tomatoes=true";

How to filter by file path in Google apps script

I am trying to have the following script filter by file path. Ideally this should only show results from the folder marked 'GUEST' in my drive. Right now it shows those and anything else with the shared folder ID of this root (I do not want to use the GUEST folder ID because I will later use this to filter other users accessing my drive).
My google drive file path is as follows Root/GUEST
CODE UPDATED WITH ANSWER FROM COMMENTS:
var folderId = "MyID"; // <--- Your shared folder ID
function doGet() {
var t = HtmlService.createTemplateFromFile('index');
t.data = getFileList();
return t.evaluate() .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);;
}
function getparams(e) {
return zipping(typeof(e.fileId) == "string" ? [e.fileId] : e.fileId);
}
function getFileList() {
var folderlist = (function(folder, folderSt, results) {
var ar = [];
var folders = folder.getFoldersByName("GUEST");
while (folders.hasNext()) ar.push(folders.next());
folderSt += folder.getId() + "#_aabbccddee_#";
var array_folderSt = folderSt.split("#_aabbccddee_#");
array_folderSt.pop()
results.push(array_folderSt);
ar.length == 0 && (folderSt = "");
for (var i in ar) arguments.callee(ar[i], folderSt, results);
return results;
})(DriveApp.getFoldersByName("GUEST").next(), "", []);
var localTimeZone = Session.getScriptTimeZone();
var filelist = [];
var temp = {};
for (var i in folderlist) {
var folderid = folderlist[i][folderlist[i].length - 1];
var folder = DriveApp.getFoldersByName("GUEST");
var files = folder.next().getFiles();
while (files.hasNext()) {
var file = files.next();
temp = {
folder_tree: function(folderlist, i) {
if (i > 0) {
return "/" + [DriveApp.getFolderById(folderlist[i][j]).getName() for (j in folderlist[i])
if (j > 0)].join("/") + "/";
} else {
return "/";
}
}(folderlist, i),
file_id: file.getId(),
file_name: file.getName(),
file_size: file.getBlob().getBytes().length,
file_created: Utilities.formatDate(file.getDateCreated(), localTimeZone, "yyyy/MM/dd HH:mm:ss"),
file_updated: Utilities.formatDate(file.getLastUpdated(), localTimeZone, "yyyy/MM/dd HH:mm:ss"),
};
filelist.push(temp);
temp = {}
}
}
var sortedlist = filelist.sort(function(e1, e2) {
return (e1.folder_tree > e2.folder_tree ? 1 : -1) });
return sortedlist;
}
function zipping(fileId) {
var blobs = [];
var mimeInf = [];
fileId.forEach(function(e) {
try {
var file = DriveApp.getFileById(e);
var mime = file.getMimeType();
var name = file.getName();
} catch (e) {
return e
}
Logger.log(mime)
var blob;
if (mime.indexOf('google-apps') > 0) {
mimeInf =
mime == "application/vnd.google-apps.spreadsheet" ? ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", name + ".xlsx"] : mime == "application/vnd.google-apps.document" ? ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", name + ".docx"] : mime == "application/vnd.google-apps.presentation" ? ["application/vnd.openxmlformats-officedocument.presentationml.presentation", name + ".pptx"] : ["application/pdf", name + ".pdf"];
blob = UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + e + "/export?mimeType=" + mimeInf[0], {
method: "GET",
headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: true
}).getBlob().setName(mimeInf[1]);
} else {
blob = UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + e + "?alt=media", {
method: "GET",
headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: true
}).getBlob().setName(name);
}
blobs.push(blob);
});
var zip = Utilities.zip(blobs, Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyyMMdd_HHmmss") + '.zip');
var bytedat = DriveApp.createFile(zip).getBlob().getBytes();
return Utilities.base64Encode(bytedat);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
function postLogin(event) {
var form = document.getElementById("myForm");
form.submit();
event.preventDefault();
}
</script>
<a href="" onClick="postLogin(event);" >Click!</a>
<form id="myForm" action="MYEXECLINK" target="my_iframe"></form>
<iframe id="my_iframe"name="my_iframe" style= "width: 500px; height: 50%;" frameBorder="0" style="overflow:hidden"></iframe>
I tried to use an if statement at line 61, but it could not pull the variables for some reason (I think I'm not setting up my variables correctly):
if (filelist(folder_tree == "/GUEST/"){
return sortedlist;}
else
{return null}
Does anyone know how to make this script filter by folder_tree? Hopefully by comparing it to a var (like user=guest)?
To clarify, here is the current result:
And this is the expected output:
Thanks for any help, I'll post updates as I work on it to clarify.
You want to retrieve a file list under the specific folder.
Subfolders in the specific folder are not required to be retrieved.
You want to achieve this using Google Apps Script.
I could understand like above. If my understanding is correct, how about this modification? I think that your updated script works. But I thought that your script might be able to be modified more simple. So how about the following modification?
Modification point:
In this modification, getFileList() was modified.
In your script, at first, the folder tree is retrieved. Then, the files in all folders are retrieved. But in your situation, the folder tree is not required to be retrieved. By this, your script can be modified more simple.
At first, "FileIterator" are retrieved with DriveApp.getFoldersByName("GUEST").next().getFiles(). Then, the values are retrieved from "FileIterator".
Modified script:
function getFileList() {
var folderName = "GUEST";
var files = DriveApp.getFoldersByName(folderName).next().getFiles();
var localTimeZone = Session.getScriptTimeZone();
var filelist = [];
while (files.hasNext()) {
var file = files.next();
var temp = {
file_id: file.getId(),
file_name: file.getName(),
file_size: file.getBlob().getBytes().length,
file_created: Utilities.formatDate(file.getDateCreated(), localTimeZone, "yyyy/MM/dd HH:mm:ss"),
file_updated: Utilities.formatDate(file.getLastUpdated(), localTimeZone, "yyyy/MM/dd HH:mm:ss"),
};
filelist.push(temp);
}
return filelist;
}
References:
getFoldersByName(name)
getFiles()
Class FileIterator

nodejs request url and return json, body is empty

I found an interesting solution here to get the instagram public profile photos.
var name = "smena8m",
items;
$.getJSON("https://query.yahooapis.com/v1/public/yql?callback=?", {
q: "select * from json where url='https://www.instagram.com/" + name + "/?__a=1'",
format: "json"
}, function(data) {
console.log(data);
if (data.query.results) {
items = data.query.results.json.user.media.nodes;
$.each(items, function(n, item) {
$('body').append(
$('<a/>', {
href: 'https://www.instagram.com/p/'+item.code,
target: '_blank'
}).css({
backgroundImage: 'url(' + item.thumbnail_src + ')'
}));
});
}
});
i am trying to do the same in my nodejs app:
var request = require('request');
var name = "smena8m";
var propertiesObject = { q: "select * from json where url='https://www.instagram.com/" + name + "/?__a=1'" };
var myurl = "https://query.yahooapis.com/v1/public/yql?callback=?";
var items;
request.get(myurl, { qs:propertiesObject}, function(err, response, body) {
if(err) { console.log(err); return; }
console.log("Get response: " + response.statusCode);
if (body.data.query.results) {
items = body.data.query.results.json.user.media.nodes;
items.forEach(function(n, item) {
var itemCodes = 'https://www.instagram.com/p/'+item.code;
var thumbnails = item.thumbnail_src;
console.log('here: ', itemCodes, thumbnails);
});
}
});
but my body returns empty. could somebody help me achieve the same in nodejs?
update:
response code is 200 and body is empty.
change myurl to:
myurl='https://www.instagram.com/' +name '/?__a=1';
console.log(body) then and you should be happy!

Download data as Excel file using web api and angular JS

I have a scenario to download file from the web app that uses a) Angular JS as front end b) Web api as server and the browser is IE9.
I have tried lot of plugins for converting HTML table to excel,csv but none of them worked for IE9.So i have decided generate the file in web api and download in the client.But that too does not work.
Can any one share an working example for this scenario ?
Angular JS Code:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, exportToExcelService) {
$scope.export = function () {
exportToExcelService.download().success(
function (response) {
})
.error(function (response, status) {
});
}
}).
factory('exportToExcelService', function ($http) {
var sampleAPI = {};
sampleAPI.download = function () {
return $http({
method: 'POST',
url: 'api/Sample/download'
});
}
return sampleAPI;
});
Web APi Controller code:
[HttpPost]
public HttpResponseMessage download()
{
List<Record> obj = new List<Record>();
obj = RecordInfo();
StringBuilder str = new StringBuilder();
str.Append("<table border=`" + "1px" + "`b>");
str.Append("<tr>");
str.Append("<td><b><font face=Arial Narrow size=3>FName</font></b></td>");
str.Append("<td><b><font face=Arial Narrow size=3>LName</font></b></td>");
str.Append("<td><b><font face=Arial Narrow size=3>Address</font></b></td>");
str.Append("</tr>");
foreach (Record val in obj)
{
str.Append("<tr>");
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.FName.ToString() + "</font></td>");
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.LName.ToString() + "</font></td>");
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.Address.ToString() + "</font></td>");
str.Append("</tr>");
}
str.Append("</table>");
HttpResponseMessage result = null;
// serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
byte[] array = Encoding.ASCII.GetBytes(str.ToString());
MemoryStream mem = new MemoryStream(array);
result.Content = new StreamContent(mem);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Data.xls"
};
return result;
}
public List<Record> RecordInfo()
{
List<Record> recordobj = new List<Record>();
recordobj.Add(new Record { FName = "Smith", LName = "Singh", Address = "Knpur" });
recordobj.Add(new Record { FName = "John", LName = "Kumar", Address = "Lucknow" });
recordobj.Add(new Record { FName = "Vikram", LName = "Kapoor", Address = "Delhi" });
recordobj.Add(new Record { FName = "Tanya", LName = "Shrma", Address = "Banaras" });
recordobj.Add(new Record { FName = "Malini", LName = "Ahuja", Address = "Gujrat" });
recordobj.Add(new Record { FName = "Varun", LName = "Katiyar", Address = "Rajasthan" });
recordobj.Add(new Record { FName = "Arun ", LName = "Singh", Address = "Jaipur" });
recordobj.Add(new Record { FName = "Ram", LName = "Kapoor", Address = "Panjab" });
return recordobj;
}
I found the solution by using the following code and it works like a charm.We just need to add window.location.href.
app.controller('myCtrl', function ($scope, exportToExcelService,$location) {
$scope.export = function () {
exportToExcelService.download().success(
function (response) {
window.location.href = 'api/sample/download'
})
.error(function (response, status) {
var str = 'Hello'
});
}
}).

change() for select element is not working

I am learning Nodejs with node cookbook 2nd edition.
I like this book because it is teaching us with explaining sample code which looks very practical.
The example code is part of Browser-server transmission via AJAX part
Anyway the main question is that below is in the EX code, below is index.html file
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$.get("http://localhost:8080/profiles",function (profile_names) {
$.each(profile_names, function (i, pname) {
$("#profiles").append("<option>" + pname + "</option>");
});
}, "json");
$("#formats, #profiles").change(function () {
alert("2");
var format = $("#formats").val();
$.get("http://localhost:8080/profile/" + $("#profiles").val() + "." + format,
function (profile, stat, jqXHR) {
var cT = jqXHR.getResponseHeader("Content-Type");
$("#raw").val(profile);
$("#output").html('');
if (cT === "application/json") {
$.each($.parseJSON(profile), function (k, v) {
$("#output").append("<b>" + k + "</b> : " + v + "<br>");
});
return;
}
if (cT === "application/xml") {
profile = jqXHR.responseXML.firstChild.childNodes;
$.each(profile, function (k, v) {
if (v && v.nodeType === 1) {
$("#output").append("<b>" + v.tagName + "</b> : " + v.textContent + "<br>");
}
});
}
},
"text");
});
</script>
<style>
#frm, #raw {display:block; float:left; width:210px},
#raw {height:150px; width:310px; margin-left:0.5em}
</style>
<title> INDEX </title>
</head>
<body>
<form id="frm">
Profile: <select id="profiles">
<option> </option>
</select>
<br></br>
Format:<select id="formats">
<option value="json"> JSON </option>
<option value="xml"> XML </option>
</select>
<br></br>
<div id="output"></div>
</form>
<textarea id="raw"></textarea>
</body>
</html>
Second, server.js file
var http = require('http');
var fs = require('fs');
var path = require('path');
var profiles = require('./profiles');
var xml2js = require('xml2js');
var index = fs.readFileSync('index.html');
var routes, mimes = {xml: "application/xml", json: "application/json"}
function output(content, format, rootNode) {
if (!format || format === 'json') {
return JSON.stringify(content);
}
if (format === 'xml') {
return (new xml2js.Builder({rootName: rootNode})).buildObject(content);
}
}
routes = {
'profiles': function (format) {
return output(Object.keys(profiles), format);
},
'/profile': function (format, basename) {
return output(profiles[basename], format, basename);
}
};
http.createServer(function (request, response) {
var dirname = path.dirname(request.url),
extname = path.extname(request.url),
// $.get('http://localhost:8080/profile/' + $('#profiles').val() + '.' + format
basename = path.basename(request.url, extname);
extname = extname.replace('.', ''); //remove period
response.setHeader("Content-Type", mimes[extname] ||'text/html');
if (routes.hasOwnProperty(dirname)) {
response.end(routes[dirname](extname, basename));
return;
}
if (routes.hasOwnProperty(basename)) {
response.end(routes[basename](extname));
return;
}
response.end(index);
}).listen(8080);
below is profiles.js file
module.exports = {
ryan: {
name: "Ryan Dahl",
irc: "ryah",
twitter: "ryah",
github: "ry",
location: "San Francisco, USA",
description: "Creator of node.js"
},
isaac: {
name: "Isaac Schlueter",
irc: "isaacs",
twitter: "izs",
github: "isaacs",
location: "San Francisco, USA",
description: "Former project gatekeeper, CTO npm, Inc."
}
};
I think at index file $("#formats, #profiles").change(function () { is not working.
I just input alert("2"); to test the code but I have never seen the alert.
I also tried to change code like
$("#formats").change(function () {,
$("#profiles").change(function () {
Both of them were not working neither.
Can you let me know what is the reason?
Either wrap your client-code in a DOM ready statement or move it to the end of the <body>. Your script is being executed before the page has rendered.

Categories