How to pull individual information from an array - javascript

I'm doing an array with Object Orientation and method creation for JavaScript and I have a question:
I made it where all of the employees display when clicking the "Show Employees" button including all of their info (It's all fictionalized by the way), however, I am having difficulties with pulling individual user's information, how do I go about clicking on an individual user and pulling only that information?
the function = showEmployee(); is where I am having the issue.
Here is the code:
<!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>Lab 9-1: Employee Database</title>
<script language="JavaScript" type="text/javascript">
// Complete the employeeObject constructor
// Remember t o add a method called showEmployee
function employeeObject(name,department,extension) {[]
this.name = name;
this.department=department;
this.extension=extension;
this.showEmployee=showEmployee;
}
// Instantiate 3 instances of employeeObject
// Important - Start your array index numbers with 1
var employees = new Array();
employees[0] = "Select Employee";
employees[1] = new employeeObject("Mai Li", "Sales", 551);
employees[2] = new employeeObject("Maria Alvarez", "Human Resources", 441);
employees[3] = new employeeObject("Tom Smith", "Marketing", 331);
len = employees.length;
function showEmployee() {
var info = ""
// Complete the showEmployee() function
alert(info);
}
function showAllEmployees() {
var info = "";
for (var i = 1; i < len; i++) {
info += "Employee: " + employees[i].name + "\n";
info += "Department: " + employees[i].department + "\n";
info += "Extension: " + employees[i].extension + "\n\n";
}
alert(info);
}
//-->
</script>
</head>
<body>
<h3>Employee Database</h3>
<hr />
<form name="empForm" id="empForm">
<strong>Select name to view information:</strong>
<select name="empName" onchange="employees[this.selectedIndex].showEmployee();this.selectedIndex=0;">
<script language="JavaScript" type="text/javascript">
for (var i = 0; i < len; i++) {
if(i == 0) document.write("<option>" + employees[i]) + "</option>";
else document.write("<option>" + employees[i].name) + "</option>";
}
//
</script>
</select>
<p>
<input type="button" value="Show All Employees" onclick=
"showAllEmployees();" />
</p>
</form>
</body>
</html>
`

Consider moving the definition of the showEmployee method into the constructor definition to put the member variables of an employee in scope.
function employeeObject(name, department, extension) {
this.name = name;
this.department = department;
this.extension = extension;
this.showEmployee = () => {
let info = `${this.name}, ${this.department}, ${this.extension}`;
// or however you wish to format info
alert(info);
}
}
Working snippet:
<!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>Lab 9-1: Employee Database</title>
<script language="JavaScript" type="text/javascript">
// Complete the employeeObject constructor
// Remember t o add a method called showEmployee
function employeeObject(name, department, extension) {
this.name = name;
this.department = department;
this.extension = extension;
this.showEmployee = () => {
let info = `${this.name}, ${this.department}, ${this.extension}`;
// or however you wish to format info
alert(info);
}
}
// Instantiate 3 instances of employeeObject
// Important - Start your array index numbers with 1
var employees = new Array();
employees[0] = "Select Employee";
employees[1] = new employeeObject("Mai Li", "Sales", 551);
employees[2] = new employeeObject("Maria Alvarez", "Human Resources", 441);
employees[3] = new employeeObject("Tom Smith", "Marketing", 331);
len = employees.length;
function showAllEmployees() {
var info = "";
for (var i = 1; i < len; i++) {
info += "Employee: " + employees[i].name + "\n";
info += "Department: " + employees[i].department + "\n";
info += "Extension: " + employees[i].extension + "\n\n";
}
alert(info);
}
//-->
</script>
</head>
<body>
<h3>Employee Database</h3>
<hr />
<form name="empForm" id="empForm">
<strong>Select name to view information:</strong>
<select name="empName" onchange="employees[this.selectedIndex].showEmployee();this.selectedIndex=0;">
<script language="JavaScript" type="text/javascript">
for (var i = 0; i < len; i++) {
if (i == 0) document.write("<option>" + employees[i]) + "</option>";
else document.write("<option>" + employees[i].name) + "</option>";
}
</script>
</select>
<p>
<input type="button" value="Show All Employees" onclick="showAllEmployees();" />
</p>
</form>
</body>
</html>

You gotta add value to the <option> and pass it's value to the showEmployee function. Check out the working snippet
<!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>Lab 9-1: Employee Database</title>
<script language="JavaScript" type="text/javascript">
// Complete the employeeObject constructor
// Remember t o add a method called showEmployee
function employeeObject(name, department, extension) {
[]
this.name = name;
this.department = department;
this.extension = extension;
this.showEmployee = showEmployee;
}
// Instantiate 3 instances of employeeObject
// Important - Start your array index numbers with 1
var employees = new Array();
employees[0] = "Select Employee";
employees[1] = new employeeObject("Mai Li", "Sales", 551);
employees[2] = new employeeObject("Maria Alvarez", "Human Resources", 441);
employees[3] = new employeeObject("Tom Smith", "Marketing", 331);
len = employees.length;
function showEmployee(i) {
var info = "";
info += "Employee: " + employees[i].name + "\n";
info += "Department: " + employees[i].department + "\n";
info += "Extension: " + employees[i].extension + "\n\n";
alert(info);
}
function showAllEmployees() {
var info = "";
for (var i = 1; i < len; i++) {
info += "Employee: " + employees[i].name + "\n";
info += "Department: " + employees[i].department + "\n";
info += "Extension: " + employees[i].extension + "\n\n";
}
alert(info);
}
</script>
</head>
<body>
<h3>Employee Database</h3>
<hr />
<form name="empForm" id="empForm">
<strong>Select name to view information:</strong>
<select name="empName" onchange="showEmployee(this.value);">
<script language="JavaScript" type="text/javascript">
for (var i = 0; i < len; i++) {
if (i == 0) document.write('<option value="">' + employees[i]) + "</option>";
else document.write('<option value="'+i+'">' + employees[i].name) + "</option>";
}
</script>
</select>
<p>
<input type="button" value="Show All Employees" onclick="showAllEmployees();" />
</p>
</form>
</body>
</html>

Related

Geo Location Trace getElementById not working

I am working on a challenge by freecodecamp, Task is to show the local weather and hence I have to get the location of the user. I can get the location from here but after printing that i was trying to getElementById of a div i have printed using JS which gives null in response. I want to get the key value pair so that i can do stuff with them. Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Location Trace | freecodecamp Challanges</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="GeoResults"></div>
<script>
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
var count = 0;
$.each(data, function(k, v) {
//JSON.stringify(j); // '{"name":"binchen"}'
table_body += '<div id=Coun_'+count+'>'+v+'</div>';
//table_body += "<tr><td id='FC_"+count+"'>" + k + "</td><td><b id='SC_"+count+"'>" + v + "</b></td></tr>";
count++;
});
$("#GeoResults").html(table_body);
});
</script>
<script>
var x = document.getElementById('Coun_1') /*= 'Dooone!!!'*/;
console.log(x);
</script>
</body>
</html>
Thanks in Advance!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Location Trace | freecodecamp Challanges</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="GeoResults"></div>
<script>
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
var count = 0;
$.each(data, function(k, v) {
//JSON.stringify(j); // '{"name":"binchen"}'
table_body += '<div id=Coun_'+count+'>'+v+'</div>';
//table_body += "<tr><td id='FC_"+count+"'>" + k + "</td><td><b id='SC_"+count+"'>" + v + "</b></td></tr>";
count++;
});
$("#GeoResults").html(table_body);
var x = document.getElementById('Coun_1').innerHTML; /*= 'Dooone!!!'*/;
console.log(x);
});
</script>
</body>
</html>

javascript addressbook in html table [duplicate]

This question already has answers here:
Document.write clears page
(6 answers)
Closed 9 years ago.
I tried to make a JavaScript address book and wanted to show it in html table, but it doesn't work. The meaning is: if i click on add contact button, i can fill data in the prompt box. after that i see the result in the table, but instead of that..there is no table! and i can't add a new contact. How can i solve this problem?
JavaScript code:
function addcontact(){
contactName = {
firstName: prompt("firstname",''),
lastName: prompt("lastname",''),
address: prompt("address",''),
phoneNumber: prompt("phonenumber",'')
};
var contact = [contactName];
function printPerson(person){
document.write(person.firstName+"<br />"+person.lastName+"<br />"+person.address+"<br />"+person.phoneNumber+"<br />");
}
function list(){
var contactLength = contact.length;
for(i=0; i < contactLength; i++){
printPerson(contact[i])
}
}
list();
};
and here my html:
<!DOCTYPE html>
<html>
<head>
<title>div insteller</title>
<meta charset="utf-8">
<style type="text/css">
#adsressbook{width:300px;}
#adsressbook td, th{ border:1px solid #000; padding:5px 10px;}
</style>
</head>
<body>
<form action='' method=''>
<table id="adsressbook">
<tr>
<th>Contacten</th>
</tr>
<tr>
<td><script type="text/javascript" src="adress/adres.js"></script></td>
</tr>
<tr>
<td><input type="submit" value="add contact" onclick="addcontact()"></td>
</tr>
</table>
</form>
</body>
</html>
Try something along the following lines:
var contacts = [];
function addcontact() {
var person = {
firstName: prompt("firstname", ""),
lastName: prompt("lastname", ""),
address: prompt("address", ""),
phoneNumber: prompt("phonenumber", "")
};
contacts.push( person );
}
function resetView() {
document.getElementById("output").innerHTML = "";
}
function printPerson( person ) {
document.getElementById("output").innerHTML +=
person.firstName + " - " +
person.lastName + " - " +
person.address + " - " +
person.phoneNumber + "<br />";
}
function listContacts() {
resetView();
var len = contacts.length;
for (x = 0; x < len; x++) {
printPerson( contacts[x] );
}
}
Here's a JSFiddle of it working: http://jsfiddle.net/nttk6/42/
It would probably be better to change printPerson() and resetView() to use the DOM rather then .innerHTML. You can also recombine the functions into 1 function again if you prefer.
The main thing is to move the contact or in my example the contacts variable out of the addContact function otherwise it is reset each time the function is called. Also you don't want to be using Document.Write().
And here's another example of it implemented as a class:
var ContactManager = {
contacts: [],
resetView: null,
appendView: null,
addContact: function(){
var person = {
firstName: prompt("firstname", ""),
lastName: prompt("lastname", ""),
address: prompt("address", ""),
phoneNumber: prompt("phonenumber", "")
};
this.contacts.push( person );
this.listContacts();
},
listContacts: function(){
var len = this.contacts.length;
this.resetView();
for( x = 0; x < len; x++ ) {
this.appendView( this.contacts[x] );
}
}
};
ContactManager.resetView = function(){
document.getElementById("output").innerHTML = "";
};
ContactManager.appendView = function( person ){
document.getElementById("output").innerHTML +=
person.firstName + " - " +
person.lastName + " - " +
person.address + " - " +
person.phoneNumber + "<br />";
};
And the JSFiddle for the class version: http://jsfiddle.net/TPxRa/6/
That is because you are using document.write(). That function is overwriting the content of your document and inserting the text you specified. What you want to do is append a row to your table.
You can check out this example (which is written in jQuery; but makes it a lot easier).

How can i put my form value in javascript array

I want to make a script where i can put my form in the javascript array invoer[] and display the total
It constantly stops working and i searched a lot, i really can't find the right way :D
This is my javascript code
var strijk = ['broek', 'hemd', 'tshirt', 'lakens', 'korte broek', 'babykledij'];
var minuten = [5, 10, 5, 6, 3, 3];
function invoerstrijk() {
document.write("<form action='' method='get' name='strijkform'>");
for (var a = 0; a < minuten.length; a++) {
document.write(strijk[a] + "<input id='" + strijk[a] + "' name ='" + strijk[a] + "' type='text' />" + "<BR>");
}
document.write("<button onclick='opgeven()'>opgeven</button>");
document.write("</form>");
}
function opgeven() {
var invoer = [];
for (var a = 0; a < minuten.length; a++) {
invoer[a] = document.getElementByI(strijk[a]).value;
}
var totaal;
for (var a = 0; a < minuten.length; a++) {
totaal += parseint(invoer[a]) * parseint(minuten[a]);
}
document.write("<input name=" + strijk[a] + " type='text' value=" + invoer[a] + " readonly />");
if (invoer != []) {
document.write("totaal aantal minuten" + totaal);
} else {
document.write("geen invoer");
}
}
my html looks likes this
<!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>
</head>
<body>
<script type="text/javascript" >
//my javasccript
</script>
<button id="B1" onclick="invoerstrijk()" >Nieuwe strijk</button>
</body>
</html>
This should work:
var strijk = ['broek', 'hemd', 'tshirt', 'lakens', 'korte broek', 'babykledij'];
var minuten = [5, 10, 5, 6, 3, 3];
function invoerstrijk() {
document.write("<form action='' method='get' name='strijkform' onsubmit='return false;'>");
for (var a = 0; a < minuten.length; a++) {
document.write(strijk[a] + "<input id='" + strijk[a] + "' name ='" + strijk[a] + "' type='text' />" + "<BR>");
}
document.write("<button onclick='opgeven()'>opgeven</button>");
document.write("</form>");
}
function opgeven() {
var invoer = [];
for (var a = 0; a < minuten.length; a++) {
invoer.push(document.getElementById(strijk[a]).value);
}
var totaal = 0;
for (var a = 0; a < minuten.length; a++) {
totaal += (parseInt(invoer[a]) * parseInt(minuten[a]));
}
// !!! this is wrong because it is out of for !!!
//document.write("<input name=" + strijk[a] + " type='text' value=" + invoer[a] + " readonly />");
if (invoer.length > 0) {
document.write("totaal aantal minuten " + totaal);
} else {
document.write("geen invoer");
}
}
Some explanation:
onsubmit='return false;' - to not send form and reload page.
invoer.push(document.getElementById(strijk[a]).value); - to put elements into array use push.
var totaal = 0; - init variable 0 bacause it is undefined.
Misspellings: Bad: parseint, Good: parseInt; Bad: getElementByI, Good: getElementById
The line with readonly input is wrong because it is out of for so a variable is not defined.
Plunker example

Create HTML table with hyperlink from JSON Object

I have an application which returns a JSONObject. I am able to get data from JSON object using below code.
<!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">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<head>
<style type="text/css">
table, td, th
{
border:1px collapse black;
font-family:Arial;
font-size :small;
}
th
{
background-color:green;
color:white;
}
.hideMe
{
/*display : none;*/
/*visibility: hidden;*/
}
</style>
<script type="text/javascript" language="jscript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
var host = "somehost";
var mystr = "http://"+ host +"/rest/bpm/wle/v1/exposed/process"; // use get for this
var ulink = "";
$(document).ready(function () {
$.get(mystr, function (data) {
var obj = JSON.parse(data);
var thtml = "<table id='proctable'>";
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function()' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
}
thtml = thtml + "</table>";
document.getElementById('contentdiv').innerHTML = thtml;
});
});
//javascript
my_function = null;
//jquery
$(function () {
function generateBPDInstance() {
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}
my_function = generateBPDInstance;
ulink = "";
})
`
</script>
</head>
<body>
<form name="myform">
<div id="contentdiv">
<table id="proctable">
</table>
</div>
</form>
</body>
</html>
The above html creates a table showing a list of the returned values. I also want to get rowIndex of hyperlink and pass value of column2 to function generateBPDInstance.
I am not so good at HTML and Jquery. Please suggest how can I get rowIndex for HTML table which is created through javascript.
Thanks in advance.
The simple way is :
change your table building to this
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "" + obj.data.exposedItemsList[i].display + "" + ulink + "";
function my_function(e){
//e is the row index and when you call document.getLementById("proctable").rows[e]; this will give you the complete row.
}
--this is a simple way, and if you want traverse the tree and get , you always have parentnode or you can use jquery $(object).parent() to get the parent of hyperlink and traverse.
You problem is "pass value of column2 to function generateBPDInstance". Why not pass it already while generating the table?
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function('" + ulink + "')' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
// ------------------------------------------------------^ pass the value
}
Add parameter to your function generateBPDInstance
function generateBPDInstance(ulink) {
//--------------------------^----
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}

How do I make this sample code from MSDN work in Chrome

MSDN gives the following Javascript code for querying the Bing Image Search API. It works fine in IE but breaks in Chrome. How can I fix it to be compatible across browsers?
MSDN JSON Code Sample (Image SourceType)
<!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>
<title>Bing API 2.0 Image Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script id="searchCallback" type="text/javascript" src="">
</script>
<script type="text/javascript">
// Replace the following string with the AppId you received from the
// Bing Developer Center.
var AppId = "AppID Intentionally Omitted";
// Bing API 2.0 code sample demonstrating the use of the
// Image SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=xbox site:microsoft.com"
+ "&Sources=Image"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Adult=Moderate"
// Image-specific request fields (optional)
+ "&Image.Count=10"
+ "&Image.Offset=0"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
var requestScript = document.getElementById("searchCallback");
requestScript.src = requestStr;
}
function SearchCompleted(response)
{
var errors = response.SearchResponse.Errors;
if (errors != null)
{
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else
{
// There were no errors in the response. Display the
// Image results.
DisplayResults(response);
}
}
function DisplayResults(response)
{
var output = document.getElementById("output");
var resultsHeader = document.createElement("h4");
var resultsList = document.createElement("ul");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
var results = response.SearchResponse.Image.Results;
// Display the results header.
resultsHeader.innerHTML = "Bing API Version "
+ response.SearchResponse.Version
+ "<br />Image results for "
+ response.SearchResponse.Query.SearchTerms
+ "<br />Displaying "
+ (response.SearchResponse.Image.Offset + 1)
+ " to "
+ (response.SearchResponse.Image.Offset + results.length)
+ " of "
+ response.SearchResponse.Image.Total
+ " results<br />";
// Display the Image results.
var resultsListItem = null;
for (var i = 0; i < results.length; ++i)
{
resultsListItem = document.createElement("li");
resultsList.appendChild(resultsListItem);
resultsListItem.innerHTML = "<a href=\""
+ results[i].MediaUrl
+ "\"><img src=\""
+ results[i].Thumbnail.Url
+ "\"></a><br /><a href=\""
+ results[i].Url
+ "\">"
+ results[i].Title
+ "</a><br />Dimensions: "
+ results[i].Width
+ "x"
+ results[i].Height
+ "<br /><br />";
}
}
function DisplayErrors(errors)
{
var output = document.getElementById("output");
var errorsHeader = document.createElement("h4");
var errorsList = document.createElement("ul");
output.appendChild(errorsHeader);
output.appendChild(errorsList);
// Iterate over the list of errors and display error details.
errorsHeader.innerHTML = "Errors:";
var errorsListItem = null;
for (var i = 0; i < errors.length; ++i)
{
errorsListItem = document.createElement("li");
errorsList.appendChild(errorsListItem);
errorsListItem.innerHTML = "";
for (var errorDetail in errors[i])
{
errorsListItem.innerHTML += errorDetail
+ ": "
+ errors[i][errorDetail]
+ "<br />";
}
errorsListItem.innerHTML += "<br />";
}
}
</script>
</head>
<body onload="Search()">
<div id="output"></div>
</body>
</html>
When I inspect the Javascript using Chrome I see the following error and warning:
Uncaught SyntaxError: Unexpected token <
Resource interpreted as Script but transferred with MIME type text/html.
The unexpected token error seems to refer to searchCallBack. It's not clear where the MIME type warning is coming from.
I don't know if the sample itself will work on Chrome, but the issue is this line:
<script id="searchCallback" type="text/javascript" src="">
You'll have to remove the "src" attribute. Chrome complains about the non-existing source.
This will fix the error:
<script id="searchCallback" type="text/javascript">
Don't bother about the MIME warning. Chrome just complains that the MIME type of the script is incorrect but this should not cause problems.
EDIT:
Here's a working solution for all browsers. Chrome & Co. don't like changing the src attribute of the script tag. Instead they prefer to get a script tag created dynamically.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Bing API 2.0 Image Sample</title>
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
// Replace the following string with the AppId you received from the
// Bing Developer Center.
var AppId = "1DB8A37DAB934B531CDC74CF614F386431D69FD3";
// Bing API 2.0 code sample demonstrating the use of the
// Image SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=xbox site:microsoft.com"
+ "&Sources=Image"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Adult=Moderate"
// Image-specific request fields (optional)
+ "&Image.Count=10"
+ "&Image.Offset=0"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
var elHead= document.getElementsByTagName("head")[0];
var oScript = document.createElement("script");
oScript.type= 'text/javascript';
oScript.src= requestStr;
elHead.appendChild(oScript);
}
function SearchCompleted(response)
{
var errors = response.SearchResponse.Errors;
if (errors != null)
{
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else
{
// There were no errors in the response. Display the
// Image results.
DisplayResults(response);
}
}
function DisplayResults(response)
{
var output = document.getElementById("output");
var resultsHeader = document.createElement("h4");
var resultsList = document.createElement("ul");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
var results = response.SearchResponse.Image.Results;
// Display the results header.
resultsHeader.innerHTML = "Bing API Version "
+ response.SearchResponse.Version
+ "<br />Image results for "
+ response.SearchResponse.Query.SearchTerms
+ "<br />Displaying "
+ (response.SearchResponse.Image.Offset + 1)
+ " to "
+ (response.SearchResponse.Image.Offset + results.length)
+ " of "
+ response.SearchResponse.Image.Total
+ " results<br />";
// Display the Image results.
var resultsListItem = null;
for (var i = 0; i < results.length; ++i)
{
resultsListItem = document.createElement("li");
resultsList.appendChild(resultsListItem);
resultsListItem.innerHTML = "<a href=\""
+ results[i].MediaUrl
+ "\"><img src=\""
+ results[i].Thumbnail.Url
+ "\"></a><br /><a href=\""
+ results[i].Url
+ "\">"
+ results[i].Title
+ "</a><br />Dimensions: "
+ results[i].Width
+ "x"
+ results[i].Height
+ "<br /><br />";
}
}
function DisplayErrors(errors)
{
var output = document.getElementById("output");
var errorsHeader = document.createElement("h4");
var errorsList = document.createElement("ul");
output.appendChild(errorsHeader);
output.appendChild(errorsList);
// Iterate over the list of errors and display error details.
errorsHeader.innerHTML = "Errors:";
var errorsListItem = null;
for (var i = 0; i < errors.length; ++i)
{
errorsListItem = document.createElement("li");
errorsList.appendChild(errorsListItem);
errorsListItem.innerHTML = "";
for (var errorDetail in errors[i])
{
errorsListItem.innerHTML += errorDetail
+ ": "
+ errors[i][errorDetail]
+ "<br />";
}
errorsListItem.innerHTML += "<br />";
}
}
</script>
</head>
<body onload="Search()">
<div id="output"></div>
</body>
</html>

Categories