从动态javascript动态加载php


Load php dynamically from a dynamic javascript

如何使用动态加载的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); 
}

. js(服务器端)

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

index . php(服务器端)

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

但是它不提醒任何。

使用ajax和json:

sample . html

<div onClick = "getThis()"></div>
my.js (inside 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"));

你必须把你的js文件附加到这个

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

所以当脚本文件加载时它将执行jQuery ready函数中的代码

我认为你使用jquery $.get()的方式是错误的。至少我没见过这样用过,所以你需要把index。php改成:

<?php
    $_SESSION['user'] = "rob098";
    echo json_encode($_SESSION['user']);
    header('Content-type: application/json');
?>