简体   繁体   中英

Calling Javascript function inside controller action -YII

I'm trying to call Javascript function inside controller action method, Is there any right way to call setTimeout() to be invoked on certain condition inside controller action method ?

window.setTimeout(function() {  
    alert("test");
    $.ajax({
        type: "POST",
        url:    "'.$this->createUrl("/operator/createViopNode/").'",
        data: {
            id: '.$bc_id.',
            callid:"'.$num.'",
            taskid:'.$this->taskid.'
        },
        success: function(msg){
            var ifrm = document.getElementById("frame");
            ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
            ifrm.document.open();
            ifrm.document.write(msg);
            ifrm.document.close();
        },
        error: function (jqXHR, textStatus, errorThrown){
            alert("" + textStatus + ", " + errorThrown);
        }
    });     
}, parseInt('.$tps_call.'));

I need to write above js function inside controller action method, how to write this ?

Index.csHtml

function abc()
 {
   alert("called")
 }

now Ajax Call function

function ExecuteAjax(URL,Data,Success)
{
    try {
        $.ajax({
            type: "post",
            url: URL,
            data: Data,
            contentType: "json",
            success: function (data) { if (typeof Success == "function") { Success(data); } }
        })
    } catch (e) {
        alert(e.message)
    }
}

Call ajax like this

 ExecuteAjax("/Home/FillColorDropDown", "", function (data) {
            eval(data.script);
        });

return from controller

      if(demo=="true")//put condition here whatever you want
       {
         string strscript="abc();";
       }
      protected JObject jobj = new JObject();
      jobj.Add("Script", strscript);
      return Json(jobj);

Execute js function when controller return success

You should register your javascript function like this:

function actionTest(){
  $cs = Yii::app()->clientScript;
  $cs->registerScript('my_script', 'alert("Hi there!");', CClientScript::POS_READY);
  $this->render('any_view');
}

source

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