如何响应XMLHttpRequest

How to respond to an XMLHttpRequest

本文关键字:XMLHttpRequest 响应 何响应      更新时间:2023-09-26

我使用Javascript来询问我们的应用程序(这是在谷歌应用程序引擎),如果用户想要上传的文件已经在他的文件列表中(他将覆盖)。

我知道如何发送请求,但是我如何使用Python从服务器创建响应?

这是请求:

var req = new XMLHttpRequest();
  req.open('POST', 'https://safeshareapp.appspot.com/upload', async);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  req.setRequestHeader("Content-length", body.length);
  req.setRequestHeader("Connection", "close");
  if (async) {
    req.onreadystatechange = function() {
      if(req.readyState == 4 && req.status == 200) {
        var response = null;
        try {
         response = JSON.parse(req.responseText);
        } catch (e) {
         response = req.responseText;
        }
        callback(response);
      }
    }
  }
  // Make the actual request
  req.send(body);

正如你所看到的,我们正在从请求中获得responseText,但我的问题是我们如何在服务器端填充responseText字段??

class MyRequestHandler(webapp.RequestHandler):
    def get(self):
        import json
        result = {"filename": xxx} // just an example, result can be any Python object
        json_obj = json.dumps(result)
        self.response.out.write(str(json_obj))