2015-04-04 51 views
2

爲什麼我的代碼不工作?JavaScript innerHTML include php

function _(x){ 
    return document.getElementById(x); 
} 

function friends(){ 
    _("right").innerHTML = '<?php include_once "friendlist.php";?>'; 
} 

結果:

<!--?php include_once "friendlist.php";?--> 

我怎樣才能解決呢?

+0

你想要什麼? – 2015-04-04 07:12:15

+0

它應該點擊加載php文件轉換爲div的朋友 – User 2015-04-04 07:13:37

+0

使用_(「right」)。innerHTML ='<?php echo include_once「friendlist.php」;?>'; – Saty 2015-04-04 07:16:04

回答

1

使用它會工作

<div id="right"> 
    <script> 
     document.write('<?php echo include_once "include.php";?>'); 
    </script> 
</div> 

或I測試下面的代碼也將工作

<body> 
    <div id ="right" > 

    </div> 
    </body> 

    <script> 
    function friends(){ 
    var x=document.getElementById("right"); 
    x.innerHTML = '<?php include_once "include.php";?>'; 
    }  
    friends();  
</script> 
+0

我怎麼做到這一點onclick? – User 2015-04-04 07:25:56

+0

@用戶檢查我更新的答案..第二個選項也適用於我你可以打電話給朋友()點擊事件 – 2015-04-04 07:31:30

+0

返回:未捕獲ReferenceError:朋友沒有定義 – User 2015-04-04 07:47:05

3

你必須做類似下面這段代碼

$(document).ready(function(){ 
    $("#your_id").click(function(){ 
    $("#your_div").load('friendlist.php'); 
    }); 
}); 
0
<script> 
$(document).ready(function(){ 
     $("#id").click(function(){ 
     $("#div").load('friendlist.php'); 
     }); 
    }); 
</script> 

試像這樣...

0

這是不可能的,因爲php在服務器上工作,而不是在瀏覽器中。 使用:

$("div").load("php_file_name")

+0

爲什麼它不可能?你有沒有測試任何例子? – 2015-04-04 07:57:03

+0

,因爲PHP需要刷新瀏覽器或AJAX請求工作 – user3252197 2015-04-04 08:05:36

+0

請試試我的答案。它會工作 – 2015-04-04 08:06:49

0

如果你的代碼可以工作,那將是嚴重違反安全的行爲。好東西是你不能通過瀏覽器注入和執行php代碼:)你可以把php標籤放在html文件中,你可以顯示它,但它甚至不會被服務器傳遞,更不用說執行它了。

上,你可以在server創建friendlist.php並另一方面肯定:

比你做你的HTML/JS在browser/client

_("right").innerHTML = ajax('http://yout_site.com/friendlist.php'); 

順便說一句,如果你使用JavaScript從服務器請求的東西,然後在瀏覽器中,它被稱爲AJAX顯示它;)

只是爲了好玩,你也可以使用http://www.upiur_site.com/friendlist.php'>來避免ajax。但是這有很多缺點。 對AJAX功能利用圖書館,寫自己的...

編輯:

我錯過了第三個選項,如果服務器設置爲解析.js文件。在這種情況下,將工作。

+0

感謝你,我確定我的friendlist.php迴應html數據 – User 2015-04-18 06:08:39