我在使 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/