ajax回应302,使用Ajax发布到Django vi时的Http302响应

在开发一个使用Ajax的Web应用程序时,遇到一个难题:当用户通过Django模板提交表单后,无法正确重定向到预期的URL。问题似乎与Django的翻译应用有关。Ajax代码用于防止表单手动提交,并向'save_applicant/'视图发送POST请求。视图函数处理表单验证和保存,并返回JSON响应。然而,服务器响应为302重定向,而不是预期的JSON。这可能是因为Django的国际化URL模式导致了错误的重定向。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我正在尝试使用ajax构建一个接受输入的web应用程序。输入被发送到Django服务器端,我很难获得正确重定向的url。我知道目前的问题与django翻译应用程序有关。在

以下是相关章节。在

Ajax$(document).ready(function(){

$('#applicant_form').on('submit', function(event){

event.preventDefault() //this will stop the file from submitting the form manually.

$.ajax({

url :'/save_applicant/', // the endpoint

type : "POST", // http method

data : { the_post : "Yay" }, // data sent with the post request

dataType: "json",

// handle a successful response

success : function(json) {

console.log("success"); // another sanity check

},

// handle a non-successful response

error : function(xhr,errmsg,err) {

$('#results').html("

Oops! We have encountered an error: "+errmsg+

" ×

"); // add the error to the dom

console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console

}

});

});

});

HTML/DJANGO模板

^{pr2}$

视图.pydef save_applicant(request):

if request.method =='POST':

id = None

if 'applicant' in request.session:

id = request.session['applicant']

applicant_form = ApplicantForm(request.POST)

if applicant_form.is_valid():

session_applicant = applicant_form.save(commit=False)

if id:

session_applicant.id = id

else:

session_applicant.save()

request.session['applicant'] = session_applicant.id

return HttpResponse(json.dumps({'status':'applicant_saved'}), content_type='application/json')

else:

return HttpResponse(applicant_form.errors.as_json(),content_type='application/json')

else:

return HttpResponse(json.dumps({'status':'not_post'}),content_type='application/json')

网址.pyfrom django.conf.urls import include, url

from django.contrib import admin

from django.conf.urls.i18n import i18n_patterns

urlpatterns = [

]

urlpatterns += i18n_patterns(

url(r'^$', 'plan_b_profile.views.home', name='home'),

url(r'^save_applicant/','plan_b_profile.views.save_applicant',name='save_applicant'),

url(r'^admin/', include(admin.site.urls)),

)

命令行[21/Aug/2015 20:53:43]"POST /save_applicant HTTP/1.1" 302 0

[21/Aug/2015 20:53:43]"GET /en/save_applicant/ HTTP/1.1" 200 22

再次感谢!在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值