index.html内容如下:
<html lang="HTML5">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Run JavaScript Server</title>
<script type="text/javascript">
//请求服务端的test.php,执行其输出的js脚本
function run() {
var script = document.createElement('script');
script.setAttribute('src', 'test.php');
document.querySelector("head").appendChild(script);
}
</script>
</head>
<body>
<button onclick="run()">发起请求</button>
</body>
</html>
test.php内容如下:
<?php
header('Content-Type: application/javascript; charset=UTF-8');
echo <<<EOF
function handler(data) {
alert(data);
}
handler('Hello World')
EOF;
本文介绍如何使用HTML和JavaScript编写一个脚本,通过`<script>`标签从前端发起请求到后端的test.php,执行返回的JavaScript代码。重点在于处理跨域问题并展示前后端交互示例。
7007

被折叠的 条评论
为什么被折叠?



