【问题标题】:How to respond to an XMLHttpRequest如何响应 XMLHttpRequest
【发布时间】:2012-01-17 08:46:58
【问题描述】:

我正在使用 Javascript 来询问我们的应用程序(在 Google App Engine 中)用户想要上传的文件是否已经在他的文件列表中(他将覆盖)。

我知道如何发送请求,但是如何使用 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 字段??

【问题讨论】:

  • 你使用什么语言,服务器端?假设您正在使用 PHP。然后,您可以使用:<?php ...........; echo json_encode($variable_to_serialize); ?>

标签: javascript python google-app-engine xmlhttprequest


【解决方案1】:
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))

【讨论】:

  • @c4sh 如果它解决了您的问题,请单击接受答案(在答案的左侧)。如果它也真的有帮助,也upvote答案。
猜你喜欢
  • 2011-03-03
  • 2011-08-10
  • 2016-11-29
  • 2019-09-28
相关资源
最近更新 更多