Append the js code inside js file dynamically and execute - javascript

Suppose I have a code in string format:
var str = "var a = 10;b = 20;console.log(a+b);";
I need to append this string value to the existing js file(say test.js) dynamically. And also get the result or execute it.
* However, I can load the string in separate and execute it, but that's not what i need. Thanks for your kind help and advice.

You can do it as :
for example in text file you will call a function where you want to append the code as :
test.js ->
// some javascript code
myFunction();
// some javascript code
Now in main file create this function as :
var execuationCode = "var a = 10;b = 20;console.log(a+b);";
function myFunction(){
setTimeout(execuationCode, 0);
}
When nyFunction call in test.js file then it call this main file function

Related

External JavaScript file is not defined

For a web project, I've included a JavaScript file as a script src, as shown here.
<script src="xml2json.js"> //same directory as the web project
Next, I tried to invoke a method within xml2json, called xml_str2json.
downloadUrl("ship_track_ajax.php", function(data) {
var xml_string = data.responseText; //an XML string
//A parser to transform XML string into a JSON object is required.
//Use convert XML to JSON with xml2json.js
var markers = xml2json.xml_str2json(xml_string);
}
However, console log indicates "Uncaught ReferenceError: xml2json is not defined", even though xml2json is included as a script src. Can anyone tell me as to what is wrong?
You have to call the function directly in javascript without reffering the filename as like
xml_str2json(xml_string);
If the function is defined in any of the included file it will be invoked.
I hope this will solve your problem
Maybe you should try this:
var json = xml2json(parseXml(xml), " ");
See Demo from https://github.com/henrikingo/xml2json

untermitated string literal when using resources in razor

I have a razor code which is using resorces from resources.resx. When i use it in a function (java script), it shows error as "unterminated string literal". How do I use resources in my java script code? However in html part of my code it is able to get the actual value if #mynamespace.name
function check(arg)
{
...
var name = "#mynamespace.name";
...
}
You can't use Razor in javascript file, because javascript files are static. All you can do is use script section in your .cshtml file. You can make a walk-around following jcreamer898 post https://stackoverflow.com/a/9406739/4563955
// someFile.js
var myFunction = function(options){
// do stuff with options
};
// razorFile.cshtml
<script>
window.myFunction = new myFunction(#model.Stuff);
// If you need a whole model serialized then use...
window.myFunction = new myFunction(#Html.Raw(Json.Encode(model)));
</script>

Append <script> when preparing a html code for iframe: without executing

I am preparing an HTML code on memory for an Iframe, when I use append it executes the code.
html = $(parser.parseFromString($("#EHtml").val(), "text/html"));
js = '<script>' + $("#EJs").val() + '</script>';
html.find('body').append(js);
$("#EHtml").val() contains HTML code
and the append function does its job but also executes the code.
Any thoughts here?
You need to just store a reference to the string of code and do 1 of two things: either do the append interaction only when you want to run the code later, or run eval(jsString) when you want to run it.
Script tags won't execute if their [type] attribute is set to anything wacky.
<script type="wacky/non-executing">
console.log("This will not execute! You will not see this!");
</script>
Its Obvious to run script when you insert it, between script tags,Because your DOM already complete loads.
And it will run twice because you put it inside the body So when you body content canges the script ran again!
So you have to set your Script tag on head of an iframe to it will run Only when you insert it or reload,and not again an again !
I am not suggesting you to use eval() because it is dangerous to use for script evaluation,eval() is basically used for another purpose !
Use <script></script> tags to run your script and place it on head if you don't want to ran it twice .
var script = document.createElement('script');
script.innerHTML = $("#EJs").val();
iframe.contentWindow.document.head.appendChild(script);
May be this will help you..
Try using entities, like
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
};
html.find('body').append(encodeHtmlEntity(js));
to append and
var decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
decodeHtmlEntity(html.find('body').val());
to read.
Got it in the way I need.
I was trying to add the script tag without using ways around the problem - I mean I just wanted to add the tag as it is. Thanks every body for the inputs - I got the solution from your advises...
in the end I could append to the Iframe but it was executing in the main page context. What was causing the problem was using JQuery to do the appending... so here it is:
frame = document.getElementById("frame");
out = (frame.contentWindow) ? frame.contentWindow : (frame.contentDocument.document) ? frame.contentDocument.document : frame.contentDocument;
out.document.open();
out.document.write(html.find('html')[0].outerHTML);//HTML added here
//JS appended here
js=out.document.createElement('script');
js.innerHTML = 'js code here';
out.document.getElementsByTagName("body")[0].appendChild(js);
out.document.close();
I hope its useful for someone...

loading images from json file with jquery

So I have a json file which now loads text and images individually pretty fine, this is just a simple example of what I did to test if it would work:
outputc+="<li>"
outputc+=this.name+" "+this.price+"</li>";
$('#featured').append(outputc);
$("<img/>").attr('src',this.images).appendTo('#featured');
Using the above code works perfectly however i need for both of these to be wrapped with a list, so I did some searching and I found this:
$(document).ready(function(){
//loading json file
var url = "shoppingItems.json";
$.getJSON(url,function(json){
$.each(json.shoppingItem,function()
{
var output ='<li><img src= "'+this.images+'" alt ="'+this.name+'"></li>';
});
$('.items').append(output);
});
});
The above jQuery doesn't bring back anything at all, there isn't anything wrong with my json file as it's been validated and the code works if I simply alert it. This is potentially something I must be doing wrong with my output script which I can't see.
My JSON file can be found here: Json file not loading or showing alerts
Since you declare it inside the callback function as var output, the output variable is local to that callback function and vanishes once the loop is completed. Even if that wasn't the case, the use of the = operator would mean you were overwriting the previous value with each iteraction.
Try this:
var output = ""; // initialize it outside the loop
$.each(json.shoppingItem,function()
{
output += '<li><img src= "'+this.images+'" alt ="'+this.name+'"></li>';
});
$('.items').append(output);
http://jsfiddle.net/mblase75/zB5fv/

Including a javascript file inside a javascript function

I have a need to include a javascript file inside another javascript function. I dont have any html file. I am executing the javascript code inside a .NET program like this
MSScriptControl.ScriptControl js = new MSScriptControl.ScriptControl();
js.AllowUI = false;
js.Language = "JScript";
js.Reset();
js.AddCode(#"
function test(x)
{
return x+10;
}
");
I need to reference a javascript file inside the function test. Can someone help me out?
Thanks
There are no such instruction like 'include' in javascript language. So, to accomplish what you want you have to read another script content and concatinate it with the rest of code;
The code would be something like that:
var includedScript = ReadScriptFromFile("myfile.js");
var includedScript += #"function (x) { return x + 10";
js.AddCode(includedScript);

Categories

Resources