如何发送简单的ajax请求?

编程入门 行业动态 更新时间:2024-10-27 00:32:57
本文介绍了如何发送简单的ajax请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

帮助请发送ajax请求。

help please send ajax-request.

html:

<p><a id="test">Hello</a></p>

js:

$(function() { $("#test").click(function() { $.ajax({ url: "/xhr_test/", type: 'POST', dataType:"html", data: { "phone": 1, "skype": 2, "other": 3, }, error: function() { alert('Ошибка получения запроса'); }, success: function(data) { alert('ajax worked' + data); } }); }); });

urls.py:

url(r'^xhr_test/$', 'views.xhr_test', name='xhr_test'),

views.py:

def xhr_test(request): if request.is_ajax(): message = "Hello AJAX!" else: message = "Hello" return HttpResponse(message)

我在使用js发送邮件之前尝试检查数据:

I try to check the data before sending mail using js:

问题是在提交表单后,我收到消息error mes。同时到浏览器控制台输出:POST http:// localhost:8000 / xhr_test / 403(FORBIDDEN)

the problem is that after submitting the form I get the message "error mes". at the same time to the browser console output: POST http: // localhost: 8000 / xhr_test / 403 (FORBIDDEN)

请帮助修复代码

推荐答案

您还需要在您的请求中发送 CSRF 令牌。

You need to send CSRF token as well in your request.

从您的视图将csrf令牌传递给将生成您的网页的模板,然后将 csrf 令牌传回您的 ajax 呼叫,以便django将您认为是有效的连接。

From your view pass csrf token to template that will generate your web page, then pass that csrf token back with your ajax call,so that django recognises you as valid connection.

Javascript

$(function() { $("#test").click(function() { $.ajax({ url: "/xhr_test", type: 'POST', dataType:"json", data: { "phone": 1, "skype": 2, "other": 3, "csrfmiddlewaretoken": '{{ csrf_token }}' }, error: function() { alert('Ошибка получения запроса'); }, success: function(data) { alert('ajax worked' + data); } }); }); });

HTML模板

{% csrf_token %} <p><a id="test">Hello</a></p>

views.py

def xhr_test(request): if request.is_ajax(): phone = request.POST['phone'] data_to_send = {} data_to_send.update({'data':phone}) return HttpResponse(simplejson.dumps(data_to_send),content_type="application/json")

更多推荐

如何发送简单的ajax请求?

本文发布于:2023-10-12 01:11:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483338.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简单   ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!