【问题标题】:What's the best way to send user-inputted text via AJAX to Google App Engine?通过 AJAX 将用户输入的文本发送到 Google App Engine 的最佳方式是什么?
【发布时间】:2010-05-25 03:28:09
【问题描述】:

我正在使用 Google App Engine (python sdk) 进行开发,我想使用 jQuery 发送 Ajax 请求来存储问题的答案。

将此数据发送到服务器的最佳方式是什么?目前我有:

function storeItem(question_id) {
        var answerInputControl = ".input_answer_"+question_id;
        var answer_text = $(answerInputControl).text();
        $.ajax({
            type: "POST",
            url: "store_answer.html",
            data: "question="+question_id,
            success: function(responseText){
                alert("Retrieved: " + responseText);
            }
        });
    }

这需要一个问题 ID,并通过查询字符串将其提供给服务器。但是在服务器端,我无法访问我想要存储的答案控件的内容。如果没有 Ajax,我可以通过以下方式执行此操作:

class StoreAnswers(webapp.RequestHandler):
def post(self):
    question_id = self.request.get("question_id")
    answer_text = self.request.get("input_answer" + question_id)

但是当通过 Ajax 进行这个调用时,我的 answer_text 是空的。

  • 我是否需要将此控件的内容作为 Ajax 请求数据的一部分发送?
  • 是否将控件本身添加到查询字符串中?它的内容?内容可能有几百个字符长有关系吗?这是最推荐的做法吗?
  • 如果将其作为查询字符串发送,那么转义内容以使恶意用户不会损害系统的最佳方法是什么?

【问题讨论】:

    标签: jquery python ajax google-app-engine


    【解决方案1】:

    ajax 调用中的data 必须包含您要发送的所有数据——发布几百个字符绝对没有问题,并且绝对是推荐的方法。

    使用GET 代替POST -- 那个(我怀疑这就是您所说的“作为查询字符串发送”的意思)只会给你带来各种麻烦,并且违反了GET 的语义(应该仅限于“只读”查询,没有副作用的查询)。

    【讨论】:

    • 我提到了一个查询字符串,因为我认为 ajax 调用“data:”question="+question_id" 中的这一行正在构建一个查询字符串,但我想我错了。在通过 ajax 调用发送内容之前,有什么好方法可以转义内容?
    【解决方案2】:

    您的数据格式不正确:

    data: {
        question_id: question_id,
        input_answer: $(answerInputControl).text()
    }
    

    【讨论】:

    • 示例中的 ajax 请求未通过 answerInputControl 的文本发送。部分问题是我是否必须这样做,或者我是否可以从 python (self.request.get('input_answer_questionID')) 访问控件,它可以在没有 ajax 的情况下工作。感谢您提供更好的数据发送方式。
    猜你喜欢
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2011-01-01
    • 2014-01-15
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多