当使用AJAX POST请求发送JS代码时,可以通过设置请求头(Content-Type)为"text/plain"来解决。
以下是一个示例代码:
var xhr = new XMLHttpRequest();
xhr.open("POST", "url", true);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 请求成功后的操作
console.log(xhr.responseText);
}
};
var jsCode = "console.log('Hello, world!');";
xhr.send(jsCode);
在上面的示例中,我们将请求头的Content-Type设置为"text/plain",以告诉服务器我们发送的是纯文本而不是表单数据。然后,我们将JS代码作为字符串传递给send()方法。
请注意,由于安全原因,服务器可能会禁止接收和执行来自客户端的JS代码。因此,在实际应用中,请确保服务器端对JS代码进行适当的验证和过滤,以防止潜在的安全风险。