2011-12-09 65 views
0

如何使用我動態加載的javascript加載我的php在我的域中。從動態javascript動態加載php

我的示例代碼

sample.html(客戶端)

<div onClick = "getThis()"></div> 

my.js(客戶端)

function getThis(){ 
var url = "http://www.sampledomain.com/test.js" 
var script = document.createElement('script'); 
script.src = url; 
document.head.appendChild(script); 
} 

test.js(服務器端)

$.get("index.php", function(data) { 
    alert(data); 
}); 

index.php(Server-side)

<?php 

$_SESSION['user'] = "rob098"; 

?> 

<script> 
var data = '<?php echo json_encode($_SESSION['user']) ?>'; 
</script> 

但它沒有提醒任何。

回答

1

使用AJAX和JSON:

sample.html

<div onClick = "getThis()"></div> 

my.js(內sample.html)

function getThis() { 
    $.ajax({ 
    url: '/test.php', 
    dataType: 'json', 
    success: function(data){ 
     alert(data.user); //should alert rob098 
    }, 
    }); 
} 

test.php的

header('Content-type: application/json'); 
echo json_encode(array("user" => "rob098")); 
0

你必須追加你的JS文件到這個

$(document).ready(function(){ 
$.get("index.php", function(data) { 
    alert(data); 
}); 

}); 

所以當腳本文件中加載它會執行jQuery的ready函數

+0

TNX爲提示,會保留在我的頭上。但仍然沒有奏效。 –

0

我認爲你是使用jQuery $.get()走錯了路內的代碼。嗯,我從來沒有見過至少用這種方式,所以你需要你的index.php改成這樣:

<?php 
    $_SESSION['user'] = "rob098"; 
    echo json_encode($_SESSION['user']); 

    header('Content-type: application/json'); 
?> 

讓我知道如果我的幫助。

+0

還是沒有運氣,tsk。它似乎不加載我的PHP文件 –