【问题标题】:Execute php file from js more times多次从js执行php文件
【发布时间】: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


【解决方案1】:

感谢大家的帮助
我将 oReq.open("get", "../my_php/index.php", true); 移至函数 startIt 并且一切正常

var oReq = new XMLHttpRequest();

oReq.onload = function getData() {
 var result = this.responseText;
 result = JSON.parse(result);
 console.log(result);
};


const startIt = () => {
 oReq.open("get", "../my_php/index.php", true);
 oReq.send();
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    相关资源
    最近更新 更多