Ajax执行向php请求的js脚本

通常在php页面中直接echo js的脚本是可以解析执行的。例如
echo '<script type = text/javascript>alert("hello!");</script>';   

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

前端html代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ro">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Ajax tutorial</title>

<script type="text/javascript" src="script.js"></script>

</head>
<body>

<div id="context"> 
<script type="text/javascript">
  var tmp = '. date('Y-m-d H:i:s',time()).';
  document.write("Server Timestamp: "+ tmp);
</script>
</div>
<h4 style="cursor:pointer;" onclick="ajaxrequest('script.php', 'context')"><u>Test</u></h4>

</body>
</html>
 
  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 <script> tag in parameter
// then apply the eval() to execute the code in every script collected
function parseScript(strcode) {

  var scripts = new Array();      
  
  while(strcode.indexOf("<script") > -1 || strcode.indexOf("</script") > -1) {
    var s = strcode.indexOf("<script");
    var s_e = strcode.indexOf(">", s);
    var e = strcode.indexOf("</script", s);
    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<scripts.length; i++) {
    try {
      eval(scripts[i]);
    }
    catch(ex) {
      
    }
  }
}

 后端php文件

<?php

echo '<b>Text added with Ajax</b>, <i>received from PHP.</i>';

//返回第一个js代码, 显示当前时间戳信息
echo '<script type="text/javascript">var tmp = '. time().';alert("Server Timestamp: "+ tmp);</script>';

//返回第二个js代码,输出提示信息
echo '<script type="text/javascript">alert("The alert from the second JS script from PHP");</script>';
?>


你可能感兴趣的:(PHP,Ajax)