简体   繁体   中英

Escape single quote jQuery HTML

I have an ajax function calling a PHP class which should return the code in $var. Because of the single quotes in the $var string, JavaScript keeps giving back an error.

What would be the best way to send code with ajax without worrying about the characters and the number of lines in the code?

$var = ' <span onclick="propMove(\'54957_363807.jpg\',\'7242\',\'right\');" class="badge badge-grey" style="float:right;margin:5px;cursor:pointer"><i class="fa fa-arrow-circle-right"></i></span> ';

<script>   $("#container .content").html(' <?=json_encode($picsIn)?>  ');    </script>

Try the following:

$var = htmlentities($var);

This will return everything as html characters, and will not contain quotes.

In jQuery then do the following to the ajax response

function decodeEntities(encodedString) {
    var textArea = document.createElement('textarea');
    textArea.innerHTML = encodedString;
    return textArea.value;
}

var myCodeFromPHP = decodeEntities(myAjaxResponse);

Where "myCodeFromPHP" is the clean proper HTML, and "myAjaxResponse" is the htmlentities response

Hopefully this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM