简体   繁体   中英

JavaScript script tag in a JavaScript String

I have the same issue as here:

Script tag in JavaScript string

However I can not resolve the issue with the proposed solutions. I'm using datatables plugin for jquery. I tried different solutions from above thread but none work. I get a "$ is not defined" error.If I set var html to like "test" it works fine. The script in the String inserts a ActiveX control (IE) or plugin (FF) and displays data from database. In below code the var html somehow breaks the script:

function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {         
    var dataURL = "'data:chemical/smiles," + aData[0] + "'";
    var html = '<script type="text/javascript">'
        + 'cd_insertObject("chemical/x-daylight-smiles", 182, 172,'
        + '"CDCtrl' + iDisplayIndexFull + '","","True","False","True",'
        + 'dataurl='+ dataURL + ');</scr' + 'ipt>'; 

    $('td:eq(0)', nRow).html(html); // here $ causes an error       
    return nRow;
}

Note that I also tried to escape all < and > also in the opening script tag. Same issue. Any ideas how to solve?

EDIT:

Found solution but can't answer my own question so here it is:

jQuerys.html() function strips away script tags. I found that in the comments the documentation for.html().

Another issue is that the 3rd party function cd_insertObject uses document.write().

My solution was to copy+paste cd_insertObject but instead of using document write i return a string and then i put this string in

$('td:eq(0)', nRow).html(html);

Try this which was successful in Firefox

var scr="cd_insertObject('chemical/x-cdx',600,400,'rxncdxd','cdxfile.cdx',true,true)";
$('#deneme').html(eval(scr));

That error has nothing to do with your attempt to inject a <script> tag. The error "$ is not defined" means exactly that, "$" is undefined, it doesn't exist, thus you can not invoke it via $()

The likely cause is that you included this script before you have included jQuery, move the jQuery script tag above the one that loads this script to fix it.

It's also possible that you've used jQuery.noConflict() , causing $ to no longer refer to jQuery. Another possibility is that in between including jQuery and this code there is code that redefines $ to undefined:

$ = undefined;

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