Django + JQuery获取表单中的数据 + Ajax 发送数据

谁借莪1个温暖的怀抱¢ 2022-12-10 15:56 250阅读 0赞

(注意表单中都得带csrf_token)
1.方法一:通过Jquery$("#对应form表单id).serializeArray()获取表单数据,直接赋值给$.ajax中的data。

.serializeArray()方法参见jQuery ajax - serializeArray() 方法
该方法放回一个JSON对象数组。

  1. $("#postSubmit").click(function () {
  2. let data = $("#postContent").serializeArray();
  3. $.ajax({
  4. url: '/decuhub/home-post-ajax',
  5. method: 'POST',
  6. data: data,
  7. async: true,
  8. success: function (result) {
  9. console.log("post successfully!")
  10. }
  11. })
  12. })

2.方法二:通过$("#对应form表单id).serializer()获取表单数据:

  1. $("#postSubmit").click(function () {
  2. let data = $("#postContent").serializer();
  3. $.ajax({
  4. url: '/decuhub/home-post-ajax',
  5. method: 'POST',
  6. data: data,
  7. async: true,
  8. success: function (result) {
  9. console.log("post successfully!")
  10. }
  11. })
  12. })

3.方法三:不推荐

  1. $("#postSubmit").click(function () {
  2. let postContentForm = $("#postContent").serializeArray();
  3. let data = { };
  4. $.each(postContentForm, function(){
  5. data[this.name] = this.value;
  6. })
  7. $.ajax({
  8. url: '/decuhub/home-post-ajax',
  9. method: 'POST',
  10. data: data,
  11. async: true,
  12. success: function (result) {
  13. console.log("post successfully!")
  14. }
  15. })
  16. })

这种方法参见别人博客,也可,但是不推荐,$.each()方法参考jQuery.each()方法

Django的request.post获取到的值是

  1. <QueryDict: {'csrfmiddlewaretoken': ['vO34OFZtTj2Bp2ARMlXVJxZQb37CyuWR7ywaDC4QaJhHtcxB4xB9fnb2IOnbQ2AR'], 'content': ['asdfsd']}>

发表评论

表情:
评论列表 (有 0 条评论,250人围观)

还没有评论,来说两句吧...

相关阅读