Ajax
主页 > 网络编程 > Ajax >

Django使用AJAX向服务器发起请求的操作方法

2024-05-23 | 佚名 | 点击:

AJAX(Asynchronous JavaScript and XML)是一种用于创建交互式网页应用程序的技术,它允许在不重新加载整个页面的情况下向服务器发送和接收数据。通过 AJAX,网页可以异步地向服务器发起请求并在后台进行处理,然后在不刷新页面的情况下更新页面的部分内容。

具体来说,AJAX 主要由以下几个核心技术组成:

AJAX 技术的主要优点包括:

总的来说,AJAX 技术使得网页能够更快速、更动态地与用户交互,为用户提供更加流畅和友好的使用体验。

实例

在网页页面有一个信息列表,点击列表中的编辑图标后,向服务器发送请求,由视图函数处理后,更新数据库记录,并且刷新页面。

1、html文件,及其中的脚本语言如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<table class="table table-hover">

    <tr>

        <td>序号</td>

        <td>栏目名称</td>

        <td>操作</td>

    </tr>

    {% for column in columns %}

    <tr>

        <td>{{ forloop.counter }}</td>

        <td>{{ column.column }}</td>

        <td>

            <a name="edit" href="javascript:" rel="external nofollow"  rel="external nofollow"  onclick="edit_column(this, {{ column.id }})">

                <span class="fas fa-pencil-alt"></span>

            </a>

            <a name="delete" href="javascript:" rel="external nofollow"  rel="external nofollow"  onclick="del_column(this, {{ column.id }})">

                <span class="fas fa-trash-alt" style="margin-left: 20px;"></span>

            </a>

        </td>

    </tr>

    {% empty %}

    <p>还没有设置栏目,太懒了。</p>

    {% endfor %}

    </table>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

<script>

    function edit_column(element, columnId) {

        // 获取当前行的文档名称单元格

        const currentRow = element.closest('tr');

        const nameCell = currentRow.querySelector('td:nth-child(2)');

        // 获取当前文档名称

        const currentName = nameCell.textContent;

        // 弹出 Prompt 对话框,获取新的文档名称

        const newName = prompt('请输入新的栏目名称:', currentName);

        // 如果用户点击了确定并输入了新名称,更新表格中的文档名称

        if (newName !== null && newName.trim() !== '') {

            const trimmedName = newName.trim();

            // 发送 AJAX 请求更新数据库,在fetch后支出了提交的url,由该url确定由那个view函数处理提交

            fetch(`/article/update-column/`, {

                method: 'POST',

                headers: {

                    'Content-Type': 'application/json',

                    'X-CSRFToken': getCookie('csrftoken')  // Django 的 CSRF token

                },

                body: JSON.stringify({

                                current_name: currentName,

                                new_name: trimmedName

                                }) //发送到后台的是一个字典,键current_name值是column的旧名称,键new_name值是column的新名称

            }).then(response => {

                if (response.ok) {

                    // 更新成功,更新表格中的文档名称

                    nameCell.textContent = trimmedName;

                    alert('栏目名称更新成功');

                } else {

                    // 更新失败,处理错误

                    alert('更新失败,请重试');

                }

            }).catch(error => {

                console.error('Error:', error);

                alert('更新失败,请重试');

            });

        }

    }

    function del_column(element, columnId) {

        // 实现删除功能的逻辑

        console.log('删除栏目 ID:', columnId);

    }

    // 获取 CSRF token 的函数(Django)

    function getCookie(name) {

        let cookieValue = null;

        if (document.cookie && document.cookie !== '') {

            const cookies = document.cookie.split(';');

            for (let i = 0; i < cookies.length; i++) {

                const cookie = cookies[i].trim();

                if (cookie.substring(0, name.length + 1) === (name + '=')) {

                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));

                    break;

                }

            }

        }

        return cookieValue;

    }

</script>

 

2、view函数如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@csrf_exempt

@login_required

def update_column(request):

    if request.method == 'POST':

        try:

            data = json.loads(request.body)

            current_name = data.get('current_name') #提交数据字典中的current_name

            new_name = data.get('new_name') #提交数据字典中的new_name

            changed_column = ArticleColumn.objects.get(user = request.user, column=current_name)

            changed_column.column = new_name

            changed_column.save()

            return JsonResponse({'status': 'success'})

        except ArticleColumn.DoesNotExist:

            return JsonResponse({'status': 'error', 'message': 'ArticleColumn not found'}, status=404)

        except Exception as e:

            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)

    return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)

3、url如下

1

path('update-column/', views.update_column, name='update_column'),

原文链接:
相关文章
最新更新