網頁開發的階段總結(三)--JS與PHP直接互調用

來源:互聯網
上載者:User

標籤:style   http   color   os   io   java   ar   檔案   資料   

        在公司項目的改造當中,經常會遇到js與php的函數互調的情況,而實際上JS與php的設計者是不提倡這兩種語言直接進行調用的,一個是用戶端語言,一個服務端語言,兩者之間的互動往往靠的是ajax機制,get(),post()進行資料的傳遞。而且在兩者在進行直接調用,往往有以下的限制:


1、首先,php與JS之間的互調只能在同個檔案裡,對其它檔案的調用都會失敗,無論是php還是JS的。

2、php與JS之間的調用只能針對的是函數,而對變數都不能實現引用,即在"<?php    ?>"中php不能引用JS的變數, 相反在"<script>  </script>"中JS也不能引用php的變數。而通過網上搜尋說可以實現互調,有可能是瀏覽器安全色的問題,本人用的瀏覽器是Google Chrome(版本 37.0.2062.103 m),這也在從側面說明php與JS的直接互調很容易出現BUG。

3、在函數的調用時都要有返回值,php通過“echo”或“return”將數值返回,而JS通過“document.write()”或“return”將數值返回。

4、對函數的調用時,都要用一個變數將函數傳遞迴來的值進行儲存。例:在JS中 var y = "<?php JSphpTest()?>"; 在php中   $phpB = "<script> phpJSTest()</script>";注意:記得在對函數調用時要加上" "雙引號。


附上部分代碼:

     

<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title></title><script language="JavaScript" src="javascript.js"></script><script language="JavaScript">function JSTest(){   var $tmp = "Hello, JS use the same file JS function";   return $tmp;}function phpJSTest(){   document.write("Hello, php use the same file JS function");}var tmp = "php call the same file JS element"; document.write("<br/><br/><br/><br/>"); document.write("script---call---show :"); document.write("<br/>");  //use the same file js function var x = JSTest(); document.write(x); document.write("<br/>");   //use same file php function var y = "<?php JSphpTest()?>"; document.write(y); document.write("<br/>");      //use another file's  JS function   var z = fileouter();  document.write(z);  document.write("<br/>");  </script><?php    function phpTest()  {    echo "Hello, php use the same php  function";  }    function JSphpTest()  {    echo "Hello, JS use the same file php function";  }      include 'PHPcallOutfilePHP.php';      echo "<br/><br/><br/><br/>";  echo "php---call---show"."<br/>";     //php call the same file php function   $phpA = phpTest();   echo "$phpA"."<br/>";      //php use the  same file JS function  $phpB = "<script> phpJSTest()</script>";  echo "$phpB"."<br/>";     //php use external file php function   $phpC = phpcalloutfilephp();   echo "$phpC"."<br/>";?></head></html>
完整代碼:http://download.csdn.net/detail/aba13579/7874961

  

網頁開發的階段總結(三)--JS與PHP直接互調用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.