ajax执行php代码,Ajax执行向php请求的js脚本

通常在php页面中直接echo js的脚本是可以解析执行的。例如

echo '';

web页面会直接弹出警示窗。但是web页面通过Ajax向php发送http数据请求,返回的有关script语句出于安全原因却不可以直接执行。如果要在网页上执行就要做一些处理。下面就来说一下这个过程。

前端html代码

Ajax tutorial

var 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 '';

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值