javascript - 在 Google App Engine 上使用 jQuery 处理 json 表单

标签 javascript jquery python json google-app-engine

我在使 jQuery 在 GAE python 2.7 上工作时遇到一些问题。 主要问题是jQuery无法捕获服务器返回的json数据。

一个简单的评论表单,没有什么特别的:

<form action="/postcomment/" method="post" id="commentform">
  <input type="text" name="author" id="author"  onfocus="if(this.value=='Name: (required)') this.value='';" onblur="if(this.value=='') this.value='Name: (required)';" {% if name %}value="{{ name }}"{% else %}value="Name: (required)"{% endif %} size="22" tabindex="1" aria-required='true' />
  <input type="text" name="email" id="email"  onfocus="if(this.value=='E-Mail: (required)') this.value='';" onblur="if(this.value=='') this.value='E-Mail: (required)';" {% if email %}value="{{ email }}"{% else %}value="E-Mail: (required)"{% endif %} size="22" tabindex="2" aria-required='true' />
<textarea name="comment" id="comment" cols="100%" rows="10" tabindex="3"></textarea>
<input name="submit" type="submit" id="submit" tabindex="4" value="Submit" />
</form>

我的 jQuery 代码(只是为了使其更简单的结构):

$("#submit").click(function() {
$.ajax({
 dataType: 'json',
 beforeSubmit: function() {
 },
 timeout: 60000,
 error: function(request,error) {
 },
  success: function(data) {
   var obj = jQuery.parseJSON(data);
   //blah blah...
   } // End success
}); // End ajax method
});

在服务器端:

class PostComment(BaseHandler):
  def post(self):
    self.response.headers['Content-Type'] = "application/json"
    response = {'errorcode': 0}
    self.response.out.write(json.dumps(response))

结果是: 单击“提交”按钮后,我的 Firefox 3.6 浏览器显示:存在“application/json”文件,您想用什么工具打开它?

我期待 jQuery 捕获这个“json”数据并处理它。但这并没有发生。

我相信我已经快到了,但出了点问题。

最佳答案

您需要取消表单的默认操作,即提交(这会取消任何正在运行的 JavaScript AJAX 查询):

$("#submit").click(function() {
    $.ajax({
     dataType: 'json',
     beforeSubmit: function() {
     },
     timeout: 60000,
     error: function(request,error) {
     },
      success: function(data) {
       var obj = jQuery.parseJSON(data);
       //blah blah...
       } // End success
    }); // End ajax method
    return false; // Cancel default action.
});

通过返回false来自点击处理程序的正常表单操作,用于让浏览器将数据提交到 action 中指定的 URL。属性,不执行。

关于javascript - 在 Google App Engine 上使用 jQuery 处理 json 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12096150/

相关文章:

javascript - JQuery 不会选择和更改复选框的状态

javascript - 为什么 npm init 实际上会初始化一个 grunt 项目?

jquery - 使用浏览器滚动条滚动内容 div (css/jquery)

javascript - 在 canvas 和 jquery 中设置图像大小百分比

javascript - 如何在收到警报后取消表单的操作?

python - ElasticSearch导入错误: cannot import name 'Mapping' from 'elasticsearch.compat'

javascript - 如何强制事件等待 Angular.js 中的 promise 解决?

javascript - 为 Google 页面翻译指定 HTML DOM 节点(与 class=notranslate 相反)

jquery - 单击事件后元素移动

python - 使用多对一关系保存 Django ORM 对象时出现问题