在HTML中显示来自ajax响应的JavaScript可以通过以下步骤实现:
以下是一个示例代码:
<!DOCTYPE html>
<html>
<head>
<title>Ajax Response Display</title>
<script>
function displayResponse() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "ajax_response.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = xhr.responseText;
var scriptElement = document.createElement("script");
scriptElement.innerHTML = response;
document.body.appendChild(scriptElement);
}
};
xhr.send();
}
</script>
</head>
<body>
<button onclick="displayResponse()">显示响应</button>
</body>
</html>
在上述示例中,当用户点击"显示响应"按钮时,会调用displayResponse()函数。该函数创建一个XMLHttpRequest对象,并发送GET请求到"ajax_response.php"页面。在响应返回后,回调函数会将响应内容作为JavaScript代码插入到页面中。
请注意,上述示例中的URL为示意用途,实际应根据具体情况修改为正确的URL。此外,为了安全起见,应对响应内容进行适当的验证和过滤,以防止恶意代码注入。
领取专属 10元无门槛券
手把手带您无忧上云