2011-12-09 67 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文件 –