MY js页面:
$m = 77;
var xhr = new XMLHttpRequest();
xhr.open("POST", "try.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("m=" + escape(m));
php页面:
$var = $_POST['m'];
echo $var;
当我调用php页面时没有任何反应!你能帮助我吗?
只需要更改变量m以获得预期的输出
m = 77; // here what i have changed from $m to m
var xhr = new XMLHttpRequest();
xhr.open("POST", "try.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("m=" + escape(m));
你有两个问题。
在代码的顶部,您创建一个名为$m
的变量,但稍后您尝试阅读m
。
如果您在浏览器的开发人员工具中查看了控制台,那么这将抛出一个您会发现的ReferenceError
一旦你修复了这个错误,你的代码就会发出请求......但是你没有对响应做任何事情。
您应该为其添加一个load事件侦听器。
function alert_response() {
alert(this.responseText);
}
xhr.addEventListener("load", alert_response);
escape
已弃用,因为它无法正常工作。请改用encodeURIComponent
。text/html
内容类型,通过回显用户输入而不进行修改或过滤,您很容易受到XSS攻击。采取措施保护自己。