简体   繁体   中英

unexpected not defined error in javascript

I have page in which there's a function which calls a function from js file.

the code which calls function in js file:

<script language="javascript" type="text/javascript">
var qc = qc_chat;
window.onload = function()
{
qc.setup('<?php echo $p; ?>');
}
</script>

I am including qc.js file using this code:

function doThat() {
    $.ajax({
        url:    'http://www.example.com',
        type: 'GET',
        data: 'adrs='+getHost( document.domain ),
        dataType:   'jsonp',
        jsonp:  false,
        jsonpCallback: 'methodCallback',
        success: function( data ) {
            if( data.message == "yes" ) {

            } else {

        $.getScript("qc.js"); //files m including using this ajax
    $.getScript("tools.js");  //files m including using this ajax
            }
        }, 
        error: function( error ) {
            console.log( error ); 
        }
    });
}

and i am calling doThat() using <body onload="doThat();">

but i am getting the error in console Uncaught ReferenceError: qc_chat is not defined

Thanks

Since $.getScript is asynchronous, anything that depends on the script it loads must be done in its callback function. So it should be:

$.getScript('qc.js', function() {
    qc_chat.setup('<?php echo $p; ?>');
});

When I can't to edit the place where some modules connects, I use this snippet:

var waitForqcchat = setInterval(function(){
  if(typeof qcchat != 'undefined'){
    clearInterval(waitForqcchat);
    //here I sure, that module connected
    qcchat.setup('<?=$p?>');
  }
}, 200);

You should also write a logic to limit waiting if qcchat can never to be connected

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