I have an array that i want to JSON.encode and then send to jQuery, so that i can do something with the data inside the array in jQuery.
on the server side i do this
$stepsArray = json_encode($stepsArray);
But when i try to open the encoded array in my script it suddenly changes all the " with & quot;
(im working on a .twig page)
var stepsArray = '{{stepsArray}}';
I have tried te str.replace the & quot; with " but it doesnt work. I have also tried to use JSON.parse but it also doesnt de anything. Does this sound familiar to anyone?
Maybe try to use this option:
json_encode($stepsArray, JSON_FORCE_OBJECT)
What you can also try is for replacing the string in the javascript is
string.replace(/$quot;/g, '\"');
Can I ask what you mean by "opening it" in your script. What exactly do you want to do with it? jQuery might convert it to HTML friendly text in certain cases, because jQuery's main purpose is to put stuff into the DOM.
Related
I'm trying to use JavaScript to include a footer on several webpages, so if I want to change the footer, I only have to change it in one place. PHP is not available on this server and neither are server side inserts (SSI), but Perl, Python, and Tcl are available. I have been trying with document.getElementsByTagName('footer').innerHTML = "text"; but it doesn't produce text. I copied this code from dev.mozilla, and it tells me how many tags I have:
var footer = document.getElementsByTagName('footer');
var num = footer.length;
console.log('There is ' + num + ' footer in this document');
So, I don't know what's wrong with the innerHTML script. I also tried with paragraph tags and got the same results in both cases.
I reccoment using textContent instead. Se why here.
To see how it works, paste the following into your browser console while you're on StackOverflow and hit enter.
document.querySelector('.site-footer').textContent = 'Custom footer content.'
note: use querySelector with a class instead of getElementByTagName
Cheers! 🍻
Before asking this question, I had searched for Python includes without any luck, so I stopped there, but after asking this question, I thought that I should search for Perl/Ruby includes. Today, I found out that I can use the Perl use function, so I could study that and try to implement it although I am completely new to Perl. Ruby also appears capable, perhaps even more. I have no experience with Ruby either, but maybe I should start there.
I just figured out that getElementsByTagName() results in an array, so I have to refer to the footer's index with [0]:
var footerTags = document.getElementsByTagName('footer');
footerTags[0].innerHTML = "test";
Hi Guys I've been dealing with an estrange thing while trying to pass string parameters to a JavaScript function from code behind, this is what I have actually in code behind which is wrong:
thumbnail = "<a href = 'javascript:RemovePirctureDetail(" + field1 + ",'" + tempname + "');' class='label label-default' rel='tooltip'>Remove</a>";
So this is the bad result I'm getting in the browser:
Remove
Meas that for some reason when I try to pass the string parameter, the html comes out bad formatted. The result should looks like this:
Remove
I tried already send the quotation marks like this /' from code behind, it did not work neither. How can I achieve this?
Thanks.
string thumbnail = "Remove";`
You need to use \ to escape the quotes inside, not /..
With javascript attribute I wouldn't use single quote, because it could be messy
Try to change in this way:
thumbnail = "Remove";
PS: Actually, I would NEVER use single quotes with attributes, it will cause an HTML validation error, HTML is not well formed with single quotes for attributes (although with inspection tools you see double quotes.. because inspection tools have the need to work with a well formed HTML, so if you want to see the real HTML of your page, view the source code (generally the option is on right-click on the page)
I have Googled my brains out and can't figure out how to make this work. Here is what I'm trying to do:
HTML:
<div id=derp>"Hi, my name is.."</div>
Javascript:
var div = document.getElementById('derp');
alert(div.innerHTML);
alert(div.innerText);
alert(div.textContent);
All of those alerts interpret and return the " as " in the resulting string. I want to get the raw text with " uninterpreted.
They all return:
"Hi, my name is.."
When I want to get:
"Hi, my name is.."
Is there a way to do this? Preferably without trying to use a regex to replace every instance of " with ".
It's kind of a long story of what I'm trying to do, but simply using replace() to search and replace every instance of " would be a headache to implement because of other regex matching/parsing that needs to occur.
Thanks in advance for any Javascript wizards who can save my sanity!
To quote bobince
When you ask the browser for an element node's innerHTML, it doesn't
give you the original HTML source that was parsed to produce that
node, because it no longer has that information. Instead, it generates
new HTML from the data stored in the DOM. The browser decides on how
to format that HTML serialisation; different browsers produce
different HTML, and chances are it won't be the same way you formatted
it originally.
In summary: innerHTML/innerText/text/textContent/nodeValue/indexOf, none of them will give you the unparsed text.
The only possible way to do this is with regex, or you can do an ajax post to the page itself, but that is a bad practice.
I prepared some days ago a bin with some different approaches: http://jsbin.com/urazer/4/edit
My favorite:
var text = "");
var html = text.replace(/[<&>'"]/g, function(c) {
return "&#" + c.charCodeAt() + ";";
});
I have no idea what im doing wrong, but I have a JSON string with this:
jsonp443489({"content":"<!DOCTYPE html><html><head><title>Title</title></head><body><p>Hello World</p></body></html>"});
I need to parse this to be able to modify the content. Like, for example, id want to grab the <p>'s content.
Now, in jQuery if i do:
console.log($(json.content).html());
It returns Title.
If i do:
console.log($('p',json.content));
It returns [], or, an empty array.
Finally, if I do just:
console.log($(json.content));
It returns [<title>​Title​</title>​,<p>​Hello World​</p>​]
Which is fine, but then I cant do .find() or anything. Since I wont know what the HTML will be, i cant use $(json.content)[1].
Any ideas?
==UPDATE==
After hacking at this for a couple hours i decided to try XML. My example XML was:
<?xml version=\"1.0\" encoding=\"UTF-8\"?><doc><item>One</item><item>Two</item></doc>
It was giving me the same grief, then it hit me, its a JS object, not a string and jQuery is expecting a string. I went and did
$(JSON.stringify(json.content)).find('item')
And voila! I got an array of two items. I was pretty excited but then when I went and tried it with HTML again (using the JSONP return HTML snippet above):
console.log($(JSON.stringify(json.content)).find('p'));
I still get an empty array. It's driving me mad... Any more ideas?
There might be a better way, but this works (retrieves the p elements):
$('<div />', {html: json.content}).find('p');
What is jsonp443489 here? Why not just do $.parseJSON ?
Once you have done that you should be able to access content inside it and then create a jquery object from that content and search in it.
var json = $.parseJSON(jsoncontent);
$(json.content).find('');// or you can add it to dom and search using $('#id')
I'm trying to set up an export function in JavaScript for a packaged web app that turns a string stored in localStorage into a plain text file for downloading. As JavaScript does not have access to the computer's file-system, I'd like to set it up so that it create a blank text file (or, failing that, a simple HTML page) and open in in the web-browser; as it wouldn't be accessing any file-systems I was hoping this would be possible.
I was thinking of using a Data URI scheme to open the localStorage as plain text, such as the following:
function exportFile() {
window.open("data:text/plain;charset=utf-8," + localStorage.WebAppData);
};
But it's much slower than I expected, which I guess is because it's sticking the whole document in the URL box. Though probably not an issue with the code, some web browsers, like Google Chrome, won't let me save the resulting file. (And for some reason all the line-breaks have turned into spaces....)
Any suggestions to fix these problems or better ways of doing a similar function will be greatly appreciated!
Did you try something like:
window.open("data:text/plain;charset=utf-8," + localStorage.WebAppData);
For the download, I guess you need a round trip to a server, that will set a mime/type that will make the download box to pop up.
EDIT:
If you use localStorage, may be window.postMessage is available in your environment and could help for speed.
In order to retain line-breaks in the data exported with window.open you may wrap up your data with encodeURI:
var data1 = "Line \n break. And \r\n another one";
window.open("data:application/octet-stream, " + encodeURI(data1));
Otherwise you may export your data encoded in base64 with the btoa function:
var data1 = "Line \n break. And \r\n another one";
window.open("data:application/octet-stream;base64, " + btoa(data1));
Not really a solution, rather a work-around, but your question and the answer by #Mic lead me down this route:
Just use data:text/html as then you can put in line breaks using <br />
I tried everything else (all combinations of unicode characters, etc, ) to get line breaks in text/plain but couldn't get them to show up. document.write() and document.body.textContent(), etc also suffer from the same problem. Line breaks just get ignored.
Since Chrome won't let you save the popup window anyway, the only way to get text out of it is copy and paste so there is no benefit of using text/plain over text/html
In web browsers that will let you save the page (Firefox) you can choose to save the page as text, rather than HTML and so you still get the same end result.
EDIT: This approach works in Chrome, but not Firefox
win = window.open("", "win")
win.document.body.innerText = "Line \n breaks?"
Have to use innerText though. InnerHTML or textContent remove the line breaks. This works on both:
win = window.open("", "win")
win.document.body.innerHTML = "<pre>Line \n breaks?</pre>"
So perhaps you could just wrap everything in <pre> tags? Although I guess both of these have the same "problem" as the ` suggestion in that it's actually creating a HTML document rather than a text/plain one.