【问题标题】:AJAX is returning readystate=1AJAX 正在返回 readystate=1
【发布时间】:2020-10-20 12:19:46
【问题描述】:

我是新手。我正在将 FLASK 与 python 一起使用。从 flask 方法中,我试图在 AJAX 调用中返回一个 html 表行。

HTML Page has

<div>
<table id="tableQuestions">

</table>
//AJAX Requests to get
function loadQuestions(){

  var xmlHttp = new XMLHttpRequest();

   xmlHttp.onreadystatechange = function() {
   alert(xmlHttp.readyState + " " + xmlHttp.status);
   if (xmlHttp.readyState==4 && xmlHttp.status == 200) {
       var response = xmlHttp.responseText;
       console.log(response);
       document.querySelector("#tableQuestions").innerHTML=response;
     }
   xmlHttp.open("GET", '/gS', true);
   xmlHttp.send(null);

  }
}

Flask 路由有

#test.mix() returns html table rows

@gbp.route('/gS')
def gS():
    test=mn()
    response = make_response(test.mix(quesCount=4),200)
    response.mimetype="text/html"

在 Safari 调试器中,我可以看到 responseText 具有来自服务器的表数据,但 readystate 保持为 1 且 status =0

您能否建议我如何解决这个问题?

【问题讨论】:

  • 您面临什么问题?如果readyState1 那么它不会进入你的if 语句。在更改阶段的请求/响应之后,它将变为4

标签: javascript python-3.x ajax flask xmlhttprequest


【解决方案1】:

你有

xmlHttp.open("GET", '/gS', true);
xmlHttp.send(null);

在您的 xmlHttp.onreadystatechange 回调函数中,这可能会导致奇怪的效果。

尝试看看这样的东西(未经测试)是否表现更好:

//AJAX Requests to get
function loadQuestions() {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open("GET", '/gS', true);
  xmlHttp.onreadystatechange = function() {
    alert(xmlHttp.readyState + " " + xmlHttp.status);
    if (xmlHttp.readyState==4 && xmlHttp.status == 200) {
      var response = xmlHttp.responseText;
      console.log(response);
      document.querySelector("#tableQuestions").innerHTML=response;
    }
  }
  xmlHttp.send(null);
}

【讨论】:

  • 谢谢!太傻了,我没注意到我放错了大括号
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
相关资源
最近更新 更多