Javascript function not changing <pre> innerHTML? - javascript

So I have a simple setup going here where I load up a file (A blender .obj file) and display it. Then I call this function:
function parseFile(){
var fileText = $('#file').html();
var fileLine = fileText.split("\r\n");
$('#file').html(fileLine[5]);
}
Which should make it so it displays the 6th line of the file, but it still displays the whole file. How do I make it split the lines like they are in the actual file?
Edit: Just so everyone know's I'm loading the file like this: $('#file').load('model.obj');

The call to .load() is asynchronous. The method will return, but the content will be available somewhen in the future. You'll need to use a callback:
$('#file').load('model.obj', function(response, status) {
alert("Now the file is loaded");
parseFile();
});
alert("Loading the file just began, nothing available by now");
Or more narrative, using the deferred interface:
$('#file').load('model.obj').then(parseFile);
If you need/want to parse the server response anyway, it might be a better to use $.ajax() directly instead of loading it into a innerHTML and reading from there... You even could use a dedicated dataFilter for the blender.obj file type.

Maybe it is only a problem with '\n'
Try this :
var fileLine = fileText.split("\n");

Try wrapping your call like this $(parseFile()); and make sure your HTML actually contains an element with the id of file.

Related

Sharing Data Between Javascript Files

I have a script that generates a JSON formatted string. I want to use the data contained in this string in another script. I'm not sure where to even start. I've thought about running both scripts from the same directory and somehow outputting the JSON data into a text file and then loading it into the second script but this seems like more of a workaround than an actual solution. Is it possible to somehow call the second script from the first and pass it the data? Much like passing data between functions in a single script?
FWIW I have tried simply combining the functions the two scripts perform into one, but this has caused me countless headaches with no progress. For simplicity sake I'd prefer to keep the functions performed by each script separate (apart from the obvious data sharing requirement!).
Any advice or a point in the right direction would be greatly appreciated.
If JSON data is less than 5 mb then you can use localStorage to save the output in browser.
In first js file:
function fOne(){
var jsonStr = ''; //insert some json data here
localStorage.setItem("myJson", JSON.stringify(jsonStr)); //save data
}
In your second js file:
function fTwo(){
if (localStorage.getItem("myJson") !== null) {
var passedJson = localStorage.getItem("myJson"); //get saved data anytime
}
}
It is hard to say without some code to reference but maybe just a global variable with a check if its null.
var myJsonString = null;
function one () {
var jsonString = "[]";
myJsonString = jsonString;
}
function two () {
//string not set so bail
if (myJsonString === null) { return; }
}
So it actually depends what environment you are programming in. If its a web browser, all of the code is in the global space actually and is run in order. so if you have <script src="file1"> then <script src="file2"> in your html file, and you put x = 10 in the first file and use it in the second, you will have no problems. If you are using node.js, I can post a solution for that as well, just let me know.
(btw if you put x = 10 in the second file and reference it from the first it will throw an error)
There are ways of avoiding this, such as using a document.ready function or wrapping things in functions and then calling them at the end. You need to make sure that functions and variables are created before being used (this is a common mistake beginners make and are confused by)

Load JSON before anything else

I'm trying to load the JSON before anything else loads, because I need to access the JSON immediately when a browser connects to the server.
This is how I load my json
$.getJSON('icons.txt', function(iconData) {
icons = iconData;
});
How can I make it so javascript loads the json first before anything else? or at least makes it so that it's loaded before the user connects.
Just put all your other code inside function(iconData) {icons = iconData;}); callback function, it will be executed after the JSON will be fetched.
If you put your tag in the head of your HTML, it should be executed at first.
Maybe duplicate of: Load javascript before rendering page?
The code loaded on the head, and then set to synchronize loading
$.ajaxSettings.async = false;
$.getJSON(url, data, function(data){ });

Managing Html text in popup

I'm using OpenLayer popup.
when initializing it, there a parameter required to contain the html displayed in the popup.
this parameter is javascript string.
I have a conflict, on the one hand the html text is long so I prefer to place it in html file and read the file to the variable.
On the other hand, the html depends on other local variables, so if I leave it on its place I can concatenate some strings and local variables to compose the final variable containing the html text. but it is very long and ugly code...
Maybe experienced javascript programmers can help me to find a design solution to this problem?
thanks
As you are using OpenLayers you can use the OpenLayers.loadURL function to retrieve HTML from your server.
http://dev.openlayers.org/releases/OpenLayers-2.10/doc/apidocs/files/OpenLayers/Ajax-js.html
If you want to pass in local variables to server side HTML you can set up a simple handler that accepts variables, and integrates these into some static HTML (using string formatting or a template).
If you are using .NET then a .ashx file can do this. See http://dotnetperls.com/ashx for an example.
Another solution is to use an Ajax request to load your file, and then print the content inside the popup.
Using JQuery:
$.get('myfile.php',function(content){
var popup = new OpenLayers.Popup("popupid",
new OpenLayers.LonLat(mouseX,mouseY),
new OpenLayers.Size(360,200),
content,
true);
map.addPopup(popup);
});
When the Ajax request is completed, you can create the popup and fill it with the file content previously loaded.
I would recommend geographikas solution, and also try to use different js-classes to improve maintainability and readability. Don't do everything in the same object, make your own popup object that inherits from or uses OpenLayers.Popup.Anchored or something, and make the Ajax server call from there. This way you won't clutter your other code with this. Also makes it easy to reuse and substitute when needed.
I would go for something like this (untested!):
mynamespace.mypopup = function(o) {
var size = new OpenLayer.Size(100, 70);
var icon = new OpenLayers.Icon(); // Fill it
var popup = new OpenLayers.Popup.Anchored(o.id, o.lonlat, size, getContent(), icon, false, null);
var getContent = function() {
// ajax call
// return a string
}
return popup;
}
in a file called "mypopup.js"
and call it with:
var popup = new mynamespace.mypopup({id: 'whatever', lonlat: myLonLat});

JMeter modifying output to file from XML Stream

I'm attempting to write a JMeter script which after receiving and XML response from a server, extracts a string from it on the fly (drops the first part of the response) and writes it to a file.
Currently I use a Save Response Data to write to ChannelData_UAT_1 (filename). All good, it writes happily.
Then I add a BSF PreProcessor BEFORE it, and use javascript to try and extract the string. It's a bunch of XML tags, I want everything from "<Markets>" onwards.
I use:
function extract_markets(str)
{
marketIndex = str.indexOf("<Markets");
__log(marketIndex);
length = str.length;
marketString = str.substring(markeIndex, length-1);
return str;
}
vars.put('ChannelData_UAT_1', extract_markets(vars.get('ChannelData_UAT_1')));
As far as I can tell, ChannelData_UAT_1 is the variable the data is in. However this is only mentioned in the Save Response Data. But I can't do it afterwards otherwise it'll have already written to the file.
The current performance is for it to receive the response and write to the file. No filtering is done - as if my javascript didn't exist.
Anything small or obvious that I've missed? Suggestions?
I believe the issue stems from the fact that ChannelData_UAT_1 is not a variable and how Save Response Data works.
ChannelData_UAT_1 is the file name, not the content of the file.
You need to modify the contents of the "Response". You can replace the value of the page response with the value of your function.
I think the code would look something like this:
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.samplers.SampleResult;
prev.setResponseData(extract_markets(vars.get('ChannelData_UAT_1')));
Source:
http://www.javadocexamples.com/java_examples/org/apache/jmeter/samplers/SampleResult/

How to make JS execute in HTML response received using Ajax?

I have following workflow
div on the page is used
on users operation request is done
to server side page whose html is
retrived using ajax and dumped into
the div
With html markup some JavaScript is
also dumped however that is not
getting executed.
Why is so ? What could be the possible fix ?
Though i avoid doing things like this but in some old code implementations like these are very common.
Scripts added using .innerHTML will not be executed, so you will have to handle this your self.
One easy way is to extract the scripts and execute them
var response = "html\<script type=\"text/javascript\">alert(\"foo\");<\/script>html";
var reScript = /\<script.*?>(.*)<\/script>/mg;
response = response.replace(reScript, function(m,m1) {
eval(m1); //will run alert("foo");
return "";
});
alert(response); // will alert "htmlhtml"
​
This will extract the scripts, execute them and replace them with "" in the original data.

Categories

Resources