开发者

How to call a Javascript function using Cakephp

I have a function in my view(aval_comp.ctp). When I do a calculation in is function on the controller, I want to call my Javascript function.

Js Function:

<script type="text/javascript">
   开发者_Python百科 function calculateTotal(){
         var total = document.getElementById('valor1').innerHTML*1 + document.getElementById('valor2').innerHTML*1 + document.getElementById('valor3').innerHTML*1 + document.getElementById('valor4').innerHTML*1 + document.getElementById('valor5').innerHTML*1 + document.getElementById('valor6').innerHTML*1;
         document.getElementById('total').innerHTML = total;
     }
 </script>

How do I call that function in the Controller?


Well talelcool is not quite right.

You can call javascript functions from php but it is highly discouraged and not how you should use the functions. PHP is server, JS is client, never mix the two!

Anyway, if in the php you echo out this:

<?php
echo "<script>calculateTotal()</script>";

?>

That should work. It's not perfect but if you put it at the end of the .php page it should call it.

The reason it might not work is it MAY try to call the function before the browser has had time to define it. If your are having that problem let me know :)

BUT

As previously stated, you should do this on the server. If you want to use values on the screen that have just been input, you can use AJAX. I suggest learning jQuery for this, as it will help you in alot of other areas as well.


You can't , Javascript & php are not executing on the same context, see php execute in the server , it sort of compile your code & provide a html page that is sent to client (here the browser) along with javascript & css . after that the browser execute the javascripts code.

i suggest tou simply try to rewrite your function on php . it seems its doing the total wich is more simple to do using a loop lik For().


CakePHP has lot of similarities to ruby-on-rails, but it is very unfortunate that there is no decent way to fire JS functions via controller against xhr requests in cake as happens in rails. But here is how it would work for you:

var $components = array('RequestHandler');
function async_fetch(){
   if($this->ResquestHandler->isAjax()) {
      $this->autoRender = false; // <-EDIT
      echo "<script type=\"text/javascript\">  function calculateTotal(){ var total = document.getElementById('valor1').innerHTML*1 + document.getElementById('valor2').innerHTML*1 + document.getElementById('valor3').innerHTML*1 + document.getElementById('valor4').innerHTML*1 + document.getElementById('valor5').innerHTML*1 + document.getElementById('valor6').innerHTML*1;document.getElementById('total').innerHTML = total;}</script>";
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜