通常在php页面中直接echo js的脚本是可以解析执行的。例如
echo '';
web页面会直接弹出警示窗。但是web页面通过Ajax向php发送http数据请求,返回的有关script语句出于安全原因却不可以直接执行。如果要在网页上执行就要做一些处理。下面就来说一下这个过程。
前端html代码
Ajax tutorialvar tmp = '. date('Y-m-d H:i:s',time()).';
document.write("Server Timestamp: "+ tmp);
Test
Ajax部分:
// 根据浏览器创建 XMLHttpRequest 对象。
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) {// Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) {// for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// 向php文件发送POST请求,显示接收到的结果
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp();
request.open("POST", php_file, true);
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var resp = request.responseText;
document.getElementById(tagID).innerHTML = resp;
//document.write(resp);
parseScript(resp);
}
}
}
// this function create an Array that contains the JS code of every
// then apply the eval() to execute the code in every script collected
function parseScript(strcode) {
var scripts = new Array();
while(strcode.indexOf(" -1) {
var s = strcode.indexOf("
var e = strcode.indexOf("
var e_e = strcode.indexOf(">", e);
// Add to scripts array
scripts.push(strcode.substring(s_e+1, e));
// Strip from strcode
strcode = strcode.substring(0, s) + strcode.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i
try {
eval(scripts[i]);
}
catch(ex) {
}
}
}
后端php文件
echo 'Text added with Ajax, received from PHP.';
//返回第一个js代码, 显示当前时间戳信息
echo '';
//返回第二个js代码,输出提示信息
echo '';
?>