如何在不刷新页面的情况下呈现字段请求? [英] How to render a field request without refreshing the page?

查看:71
本文介绍了如何在不刷新页面的情况下呈现字段请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含几个字段的表单,第一个是一个人输入其ID号的地方,该ID与一个单独的模型关联以进行验证.我创建了此函数 get_employee_name ,该函数根据其他模型的ID返回名称,但是我不确定如何在页面顶部显示该名称,而无需在该人之后刷新选项卡/点击了吗?我对html不太熟悉,但是我正在阅读ajax GET请求可以解决问题,但是我不确定如何实现.

I have a form with a few fields, the first being where a person enters their ID #, which is tied to a separate model for verification. I made this function get_employee_name, which returns the name based on the ID from the other model, but I'm not sure how to display it in the page, right on the top, without refreshing after the person tabs/clicks out? I'm not too familiar with html, but I was reading an ajax GET request would do the trick, but I'm not sure how to approach this.

这基本上是为了让此人知道他们输入的ID号与他们的姓名相匹配,然后再继续填写其余部分.

This is basically so the person knows that the ID # they entered matches their name before proceeding to fill the rest out.

views.py

class EnterExitArea(CreateView):
    model = EmployeeWorkAreaLog
    template_name = "enter_exit_area.html"
    form_class = WarehouseForm

    def form_valid(self, form):
        emp_num = form.cleaned_data['adp_number']
        area = form.cleaned_data['work_area']
        station = form.cleaned_data['station_number']

        if 'enter_area' in self.request.POST:
            form.save()
            return HttpResponseRedirect(self.request.path_info)

        elif 'leave_area' in self.request.POST:
            form.save()
            EmployeeWorkAreaLog.objects.filter(adp_number=emp_num, work_area=area, station_number=station).update(time_out=datetime.now())
            return HttpResponseRedirect(self.request.path_info)


def get_employee_name(request):
    adp_number = request.POST.get('adp_number')
    employee = Salesman.objects.get(adp_number=adp_number)
    employee_name = employee.slsmn_name
    return employee_name

models.py

class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
    employee_name = models.CharField(max_length=25)
    adp_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) #(max_length=50, help_text="Employee #", blank=False)
    ...

    def __str__(self):
        return self.adp_number

forms.py

class WarehouseForm(AppsModelForm):
    class Meta:
        model = EmployeeWorkAreaLog
        widgets = {
            'adp_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('adp_number').remote_field, site),
        }
        fields = ('adp_number', 'work_area', 'station_number')

enter_exit_area.html

{% extends "base.html" %}
{% block main %}
    <form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate >
        {% csrf_token %}

        <div>
            <div>
                {{ form.adp_number.help_text }}
                {{ form.adp_number }}
            </div>
            <div>
                {{ form.work_area.help_text }}
                {{ form.work_area }}
            </div>
            <div>
                {{ form.station_number.help_text }}
                {{ form.station_number }}
            </div>
        </div>

        <div>
            <div>
                <button type="submit" name="enter_area" value="Enter">Enter Area</button>
                <button type="submit" name="leave_area" value="Leave">Leave Area</button>
            </div>
        </div>
    </form>

{% endblock main %}

推荐答案

我们将在jQuery中使用ajax,因此在阅读之前请确保您拥有jQuery.

We'll use ajax, with jQuery so be sure you have jQuery before you read.

首先,您必须创建一个 GET 的终结点,然后转到urls.py&添加端点说

first, you've to create an endpoint to GET, go to urls.py & add an endpoint say

path('/myserver/getID/', views.get_employee_name, name="whatever")

现在,这叫get_employee_name对吗?现在让我们在JS中调用它而无需刷新.

now, this calls get_employee_name right? Let's now call it in JS without refreshing.

这是基本语法->

$.ajax({THIS IS A SIMPLE DICT})

ajax采用参数

  • type是请求类型
  • url这是我们上面刚刚创建的请求URL(不是完整的url,您是从网站上的位置指定终结点,因此您只需使用/myserver/getID/)
  • 它还需要data,这是包含您发布的数据的字典(是在较大的ajax字典中的字典
  • CAN 接受success,这是获得状态为200(成功)的响应后要调用的函数,并且成功函数可以具有参数response,这是您的响应
  • CAN 使用error,该函数在发生错误&后会被调用以error作为参数
  • type which is the request type
  • url which is the request URL which we just made above (not the full url, you're specifying the endpoint from where you're located on the website so you just use /myserver/getID/)
  • it also takes data which is a dictionary with your posted data (yes a dictionary inside the bigger ajax dictionary
  • it CAN take success which is a function to call after getting the response with status 200 (success) and that success function can have the parameter response which is your response
  • it CAN take error which is a function that gets called after an error & takes error as argument

足够多的谈话...

$.ajax({
    url: 'myserver/getID',
    type: 'GET',
    data: // don't specify this, we're not posting any data,
    success: function (response) {console.log(response.data)}, //this will be what returned from python
    error: function (error){console.log(error)}
})

这是一个简单的ajax请求

this is a simple ajax request

注意,如果您从python&返回了重定向从ajax接受它,它将不起作用,ajax无法重定向,请记住这一点,因为大多数时候,人们会问为什么redirect('mylink')在我从ajax返回它后不起作用.

NOTE, if you return a redirect from python & accept it from ajax, it won't work, ajax can't redirect, be sure to remember that because most of the time people ask why redirect('mylink') doesn't work after I return it from ajax.

另一个注意是使用ajax处理帖子请求时,您必须包含csrf令牌,

Another NOTE is the when dealing with post requests with ajax, you must include the csrf token which can be included by

csrfmiddlewaretoken: '{%csrf_token%}'

如果需要,您也可以使用Fetch API,甚至可以使用常规的XMLhttprequest.

You can use Fetch API too if you want, or even normal XMLhttprequest.

这篇关于如何在不刷新页面的情况下呈现字段请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆