John Smith
John Smith

Reputation: 6197

Backslash Disappears from Filename

This is my code:

<script>
document.getElementById(div').innerHTML = '<a href="javascript:void(0);" onclick="openPhpFile (\'asdasD\\Asdeqw.txt\');">efff</a>';
</script>

When the openPhpFile function runs, I alert the filename, and the \ characters are gone, even though they are doubled. addslashes() doesn't help; what can it be?

Upvotes: 1

Views: 1504

Answers (5)

DaveRandom
DaveRandom

Reputation: 88647

You should do this instead:

<script type='text/javascript'>
  (function () { // Closures are your friend
    // Declare variables
    var theDiv, theLink;
    // Create the link and assign attributes
    theLink = document.createElement('a');
    theLink.innerHTML = 'efff';
    theLink.href = '#';
    theLink.onclick = function () {
      openPhpFile('asdasD\\Asdeqw.txt');
    };
    // Get a reference to the container, empty the container and add the link
    theDiv = document.getElementById('div');
    theDiv.innerHTML = '';
    theDiv.appendChild(theLink);
  })();
</script>

Remember that if you are echoing the from PHP inside double quotes, you will actually need 4 backslashes. This is because PHP will also use the double backslash sequence, and would only output one. So if you want PHP to echo 2 backslashes, you need to put 4 in.

Upvotes: 3

Esailija
Esailija

Reputation: 140230

try:

var div = document.getElementById("div");

div.innerHTML = '<a>efff</a>';

div.firstChild.onclick = function () {
  openPhpFile('asdasD\\\\Asdeqw.txt');
};

Upvotes: 2

SpiRail
SpiRail

Reputation: 1415

Just wondering why you need a backslash here? Don't All OS's support (and most even prefer) forward slash? Perhaps i have been in Linux world too long.

I would just use forward slash, at least for your double-backslash (obviously not for the quotes). I would be interested to know what you are doing that means that a forward slash wouldn't work.

Upvotes: 1

Antoine
Antoine

Reputation: 5692

Have you tried putting 4 of them instead of 2 or 3 for each backslash?

Upvotes: 1

Amir Raminfar
Amir Raminfar

Reputation: 34149

If you open js console you will see that it gets turned in to asdasD\Asdeqw.txt

So try adding another slash.

'<a href="javascript:void(0);" onclick="openPhpFile (\'asdasD\\\Asdeqw.txt\');">efff</a>'

Upvotes: 1

Related Questions