Hel*_*nar 2 django ajax jquery
我试图理解Django + Jquery和Ajax如何协同工作.
它只是一个简单的/ test/url,它显示了一个输入表单,一旦提交,就会通过ajax从服务器中检索答案.
为此,我写了一个非常小的观点:
def test(request):
if request.is_ajax():
from django.http import HttpResponse
post_text = request.POST.get("post_data")
return HttpResponse("{'response_text': '"+post_text+" recieved.'}", mimetype="application/json")
else:
return render_to_response('test.html', {},context_instance =RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
我已经在urls.py上将此url规则写入我的urlpattern:
(r'^test/$', 'myapp.views.test'),
Run Code Online (Sandbox Code Playgroud)
这是我的test.html模板:
<html>
<head><title>template</title></head>
<script type="text/javascript" src="/media/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#post_form').submit(function(event){
event.preventDefault(); // cancel the default action
var form = this;
var data = {}
data.post_data = $(form).find('input[@name=our_text]').val();
$.post("/test/",
data,
function(responseData) {
alert(responseData.response_text);
},
"json"
);
});
});
</script>
<body>
<form id="post_form" method="post">
INPUT: <input type="text" name="our_text" />
<input type="submit" value="Add" />
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
一旦我填写输入字段并提交,我似乎没有在我的www.mysite.com/test/上做任何回复.可能是什么问题?
jQuery 1.4不会解析无效的JSON.正如Alex Gaynor所提到的,你的JSON是无效的,因为它使用的是单引号,而不是双引号.
手工编写JSON很愚蠢.使用库将python数据类型转换为JSON.再一次,正如Alex所说,Django已经为你发送了simplejson.或者,如果您使用的是Python2.6或更高版本,则json是标准库的一部分http://docs.python.org/library/json.html
from django.http import HttpResponse
from django.utils import simplejson
def test(request):
if request.is_ajax():
post_text = request.POST.get("post_data")
response_dict = {'response_text': '"+post_text+" recieved.'}
return HttpResponse(simplejson.dumps(response_dict), mimetype="application/json")
else:
return render_to_response('test.html', {},context_instance =RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
718 次 |
| 最近记录: |