如果想要ajax提交数据到django后台,对页面进行跳转,需要在ajax 中进行跳转,在后台进行跳转不生效
示例代码
views部分
rom django.shortcuts import render, redirect, HttpResponse # Create your views here. from day60app.form_cls import AForm import json from django.forms.utils import ErrorDict def ajax(request): if request.method == "GET": obj = AForm() return render(request, "ajax.html", {"obj": obj}) elif request.method == "POST": obj = AForm(request.POST) ret = {"status": None, "message": None} print("31----", obj) if obj.is_valid(): ret["status"] = "成功" print("35", ret) return HttpResponse(json.dumps(ret)) else: # err = obj.errors ret["message"] = obj.errors return HttpResponse(json.dumps(ret))
from 部分
from django.forms import Form from django.forms import widgets from django.forms import fields from django.forms.models import ModelChoiceField from day60app import models class AForm(Form): user_id = fields.IntegerField( widget=widgets.Select(choices=[(1, "赖英"), (2, "春云"), (3, "星星")]) ) age = fields.IntegerField()
前端页面部分
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fm" action="/ajax/" method="post" novalidate> {{ obj.as_p }} <input type="button" value="ajax提交" id="but"> </form> <script src="/static/jquery-3.1.1.js"></script> <script> $(function () { $("#but").click(function () { $.ajax({ url:"/ajax/", type:"POST", data:$("#fm").serialize(), dataType:"JSON", success:function(arg){ console.log("26----",arg); if (arg["status"] == "成功"){ window.location.href = "http://www.jd.com" } {# else:#} } }) }) }) </script> </body> </html>
时间: 2024-08-06 23:48:53