I have some JavaScript code with Servlets code, I want to move all of them (between ) to external js file, but it doesn't work, what can I do? How to modify my code if only part of JavaScript can move to external file.
<script language="JavaScript" type="text/JavaScript">
var sel = document.getElementById('sel');
var selList = [];
<%
String key = "";
String text = "";
for(int i = 0; i < master.size(); i++) {
Map option = (Map) master.get(i);
key = (String) option.get("Code");
text = key + " " + (String) option.get("NAME");
%>
selList.push({
key: "<%=key%>",
text: "<%=text%>"
});
<%
}
%>
</script>
Here two options:
1-by not using ajax
external.js
var images;
function renderImages(){
//do things for showing images here.
//images variable has images data as JSON (i suggest you this way) so you can easily iterate over list and render it.
}
jsp
<html>
<head>
<script type="text/javascript" src="external.js"></script>
<script>
images = "<%=request.getAttribute("imageDataAsJSON")%>"; //here i assume you populate request variable with your image data in JSON format. Be careful about parse errors due to ' and ".
</script>
</head>
<body>
<script>
renderImages();
</script>
</body>
</html>
2-by using ajax (you can seperate client side logic into external js code and populate data into it by doing ajax calls to server side.)
external.js
function renderImages(){
//do ajax to your servlet which returns image data as JSON.
//iterate over image data and render your html elements accordingly.
}
jsp
<html>
<head>
<script type="text/javascript" src="external.js"></script>
</head>
<body>
</body>
</html>
I'm trying to get the html of www.soccerway.com. In particular this:
that have the label-wrapper class I also tried with: select.nav-select but I can't get any content. What I did is:
1) Created a php filed called grabber.php, this file have this code:
<?php echo file_get_contents($_GET['url']); ?>
2) Created a index.html file with this content:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>test</title>
</head>
<body>
<div id="response"></div>
</body>
<script>
$(function(){
var contentURI= 'http://soccerway.com';
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
});
var LI = document.querySelectorAll(".list li");
var result = {};
for(var i=0; i<LI.length; i++){
var el = LI[i];
var elData = el.dataset.value;
if(elData) result[el.innerHTML] = elData; // Only if element has data-value attr
}
console.log( result );
</script>
</html>
in the div there is no content grabbed, I tested my js code for get all the link and working but I've inserted the html page manually.
I see a couple issues here.
var contentURI= 'http:/soccerway.com #label-wrapper';
You're missing the second slash in http://, and you're passing a URL with a space and an ID to file_get_contents. You'll want this instead:
var contentURI = 'http://soccerway.com/';
and then you'll need to parse out the item you're interested in from the resulting HTML.
The #label-wrapper needs to be in the jQuery load() call, not the file_get_contents, and the contentURI variable needs to be properly escaped with encodeURIComponent:
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
Your code also contains a massive vulnerability that's potentially very dangerous, as it allows anyone to access grabber.php with a url value that's a file location on your server. This could compromise your database password or other sensitive data on the server.
Special thanks to Raúl Monge for posting a fully working code for me.
My problem was getting JSON data from a file.json and using this data to autocomplete search on it with JavaScript. The code that finaly got it working for me is the following:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('json/telefoonnummers.json', function(json) {
$.each(json.personen.persoon,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.naam+" - "+value.telefoonnummer;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
This is the html:
<body>
<div id="content">
<input type="text" id="search" />
</div>
And this has to be included in the head:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
Thanks stackoverflow!
NEW EDIT CODE WORKING:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('data.json', function(json) {
$.each(json.persons.person,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.name;
arrayAutocomplete[index]['value'] = value.phoneno;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
</script>
Add this in head
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
This is the html
<body>
<div id="content">
<input type="text" id="search" />
</div>
</body>
why not use
var data = [
"Aragorn",
"Arwen",
....
];
since all of those data are labels?
There you go
A working example with the data structure you have.
Just initialize the autocomplete once the JSON is loaded & the data is formatted.
$( "#search" ).autocomplete({source: availableTags});
Your document ready is within your function.
Try to write your function outside of your document ready.
Then write your document ready to call your function.
Some something like this:
function loadJson() {
//alert("Whoohoo, you called the loadJson function!"); //uncomment for testing
var mycontainer = [];
$.getJSON( "data.json" , function(data) {
//alert(data) //uncomment for testing
$.each( data, function( key, val ) {
//alert("key: "+key+" | val: "+val); //uncomment for testing
array.push([key , val]);
});
});
return mycontainer;
}
$(document).ready(function(){
//alert("Boojah! jQuery library loaded!"); //uncomment for testing
var content = loadJson();
dosomethingwitharray(content);
});
Hope this helps!
Also make sure you have jQuery included in your head ( <head> </head> ):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
And add your javascript at the end of your body ( <body> </body> ).
To test if jquery does it's job try this:
<html>
<head>
<title>getting started with jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<h1>my page</h1>
<p>this paragraph contains some text.</p>
<!-- javascript at end -->
<script>
$(document).ready(function(){
//show a dialog, confirming when the document is loaded and jquery is used.
alert("boojah, jquery called the document ready function");
//do something with jquery, for example, modify the dom
$("p").append('<br /> i am able to modify the dom with the help of jquery and added this line, i am awesome.');
});
</script>
</body>
</html>
PS. Uncomment alerts for testing stuff, so you can test what happens. If you have space in your document i suggest using $.append to an div that log's all action's so you can see exactly what's going on because alert's in a loop like the .each are quite annoying! more about append: http://api.jquery.com/append/
I am kind of stuck in weird problem. i cant find the problem with the following code
<html>
<head>
<script type="text/javascript">
// Import GET Vars
document.$_GET = [];
var urlHalves = String(document.location).split('?');
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
document.$_GET[urlVarPair[0]] = urlVarPair[1];
}
}
}
var tag_tag=document.$_GET['tags'];
alert(tag_tag);
document.getElementById("resultElem4").innerHTML=tag_tag;
</script>
</head>
<body>
<p id='resultElem4'></p>
</body>
</html>
its showing the string in alert but not in html when i call it like result.php?tags=cat
Put your script tag at the bottom (right before the closing body tag). The issue is that the element resultElem4 hasn't loaded when you try to reference it using getElementById.
You just move the < script > to the end of the body.
<body><p></p><script>....</script></body>
I have this basic auto complete JavaScript that works well, but you need to hard code the web page. What I'm trying to do is send the "Autocomplete" variable data to the page using a Perl script
The working JavaScript code looks like this:
var CustomArray = new Array('an apple','alligator','elephant','pear','kingbird',
'kingbolt','kingcraft','kingcup','kingdom','kingfisher',
'kingpin','SML');
Now the new code is:
var CustomArray=new Array(Autocomplete);
And the Perl script is sending back the data to the browser looking like this:
var Autocomplete = 'an apple','alligator','elephant','pear','kingbird',
'kingbolt','kingcraft','kingcup','kingdom','kingfish er','kingpin','SML'
I also tried
var Autocomplete = ['an apple','alligator','elephant','pear','kingbird',
'kingbolt','kingcraft','kingcup','kingdom','kingfisher',
'kingpin','SML']
But I get: 'an apple','alligator','elephant','pear','kingbird','kingbolt','kingcraft','kingcup','kingdom','kingfish er','kingpin','SML' All as one string in the auto complete.
I cant seem to get it to work right. Full HTML code is below.
<html>
<head>
<script language="javascript" type="text/javascript" src="http://www.comicinvasion.com/Code/Java/Autocomplete/Autocomplete.js"></script>
<script language="javascript" type="text/javascript" src="http://www.comicinvasion.com/Code/Java/Autocomplete/Common.js"></script>
<script language="JavaScript1.2" type="text/javascript" src="http://www.ComicInvasion.com/cgi-bin/Autocomplete.pl"></script>
<script>
var CustomArray=new Array(Autocomplete);
</script>
</head>
<body>
<input type='text' style='font-family:verdana;width:300px;font-size:12px' id='ACMP' value=''/>
<script>
var obj = actb(document.getElementById('ACOMP'),CustomArray);
</script>
</body>
</html>
First, it looks like there is a typo. The id of your input element is ACMP whereas you pass 'ACOMP' to getElementById.
Second, you do not provide the source code for your Perl script. It might look like this:
#!/usr/bin/perl
use utf8;
use strict; use warnings;
use CGI();
local $| = 1;
print CGI::header(
-type => 'text/javascript',
-charset => 'utf-8',
);
print <<JS;
var Autocomplete = [
'an apple','alligator','elephant','pear','kingbird',
'kingbolt','kingcraft','kingcup','kingdom','kingfisher',
'kingpin','SML'
];
JS
With the following HTML, autocompletion works:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="http://www.comicinvasion.com/Code/Java/Autocomplete/Autocomplete.js"></script>
<script type="text/javascript" src="http://www.comicinvasion.com/Code/Java/Autocomplete/Common.js"></script>
<!-- Replace with the URI of your script -->
<script type="text/javascript" src="http://test:8080/cgi-bin/autocomplete.pl"></script>
</head>
<body>
<input type='text'
style='font-family:verdana;width:300px;font-size:12px'
id='ACOMP' value=''>
<script type="text/javascript">
var obj = actb(document.getElementById('ACOMP'), Autocomplete);
</script>
</body>
</html>
Finally, I find it curious that your JavaScript files live in a directory called Java.
Have the perl script return this:
var CustomArray = "an apple, alligator".split(',');
Or, if it has to be this it's okay too:
var CustomArray = "'an apple','alligator'".split(',');
Obviously, I omitted the rest of the items in there but you'd include all of them.