简体   繁体   English

如何在请求后保存变量的值,但在第一次加载时有不同的值?

[英]How to save value of a variable after request, but at the first load have a different value?

I have a Flask application in which the user can select a desired period.我有一个 Flask 应用程序,用户可以在其中 select 所需的时间。 The period has a start date and an end date.期间有开始日期和结束日期。 At the first load of the page, I want the start date to be the first of the current month, and the end date to be the current day.在页面的第一次加载时,我希望开始日期是当月的第一天,结束日期是当天。 I used this code to make this work, where d1 is date of start and d3 is day of end:我使用这段代码来完成这项工作,其中 d1 是开始日期,d3 是结束日期:

$('#d1').val(today.getFullYear() + "-" + ('0' + (today.getMonth() + 1)).slice(-2) + "-" + ('0' + 1));
$('#d3').val(today.getFullYear() + "-" + ('0' + (today.getMonth() + 1)).slice(-2) + "-" + ('0' + (today.getDate())).slice(-2));

I want to be able to save the period selected by user after pushing the submit button.我希望能够在按下提交按钮后保存用户选择的时间段。 For now, after the user clicks the submit button, I have the start date as 1 of the month and the end date as the current day.现在,在用户单击提交按钮后,我将开始日期设置为月份的 1,将结束日期设置为当天。 This happens no matter what different dates the user selects.无论用户选择什么不同的日期,都会发生这种情况。 After submit, I want to be able to display start and end date as the dates selected by user.提交后,我希望能够将开始和结束日期显示为用户选择的日期。 How to achieve this?如何做到这一点? I was thinking of using我正在考虑使用

$('[name=d1]').val("{{ request.form['d1'] }}");

But this resets the start date, making it mm/dd/yyyy at the very beggining, as there was no request.但这会重置开始日期,一开始就设置为 mm/dd/yyyy,因为没有请求。 How to save the date after user selects it?用户选择后如何保存日期? But letting the dates selected at the first load of page as 1 of the month and current date.但是让在第一次加载页面时选择的日期作为月份和当前日期的 1。

You plenty of options to achieve that你有很多选择来实现这一目标

If you're using Flask template engine to render the response you could set the dates before the response in the template.如果您使用Flask模板引擎来呈现响应,您可以在模板中设置响应之前的日期。

assuming that the route where you want to submit the date is /假设您要提交日期的路线是/

@app.route('/')
def index():
    start_date = request.form['start_date']
    end_date = request.form['end_date']
    ...
    return render_template('template_name.html', start_date=start_date, end_date=end_date )

in your template在您的模板中

<input type="date" value="{{start_date}}" />
<input type="date" value="{{end_date}}" />

Another option is to use localStorage directly on the client-side另一种选择是直接在客户端使用localStorage

Also, it depends whether you are using jquery submit or HTML form submit此外,这取决于您使用的是 jquery 提交还是 HTML 表单提交

if you are using jquery submit如果您使用的是 jquery 提交

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

then you should handle the change in the success callback那么您应该处理成功回调中的更改

with something like有类似的东西

$('[name=d1]').val("{{ request.form['d1'] }}");

Hope that helps希望有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM