【发布时间】:2020-12-11 19:00:38
【问题描述】:
在 javascript 中,我有一个执行 php 函数的代码:
var oReq = new XMLHttpRequest();
oReq.onload = function getData() {
var result = this.responseText;
result = JSON.parse(result);
console.log(result);
};
oReq.open("get", "../my_php/index.php", true);
const startIt = () => {
oReq.send();
};
HTML:
<button class="btn btn-primary" onclick="startIt()" type="button" >Run</button>
此代码工作正常,但只需一次,然后网站需要刷新。否则会显示错误:
InvalidStateError:对象处于无效状态。
【问题讨论】:
-
将所有内容移到您的函数中。
-
哦,谢谢。现在可以正常使用了
-
代码其实没问题,只是每次要用的时候都需要打开请求。因此,只需将行
oReq.open("get", "../my_php/index.php", true);移动到函数中即可使进一步的请求生效。重新创建 XHR 对象不是强制性的,可以重用原始对象及其负载侦听器。
标签: javascript php xmlhttprequest