【问题标题】:Save data using javascript on Otree在 Otree 上使用 javascript 保存数据
【发布时间】:2019-11-05 04:53:41
【问题描述】:

我正在尝试通过单击在 Otree 上的数据库中保存时间戳。我尝试使用不同的代码。

第一个是这个

function myFunction() {
    var n = Date.now();
document.getElementById("demo").innerHTML = n;
}

document.getElementById('n').value;

我把下一段代码放在html里:

 <p style="text-align: center;"><button class="btn btn-primary btn-large" onclick="myFunction()"  name="offer_accepted" value="True">&nbsp;A</button> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button class="btn btn-primary btn-large"  onclick="myFunction()" name="offer_accepted" value="False">B</button></p>

下一个是这样的:

function record_current_time(){
   var current_time = new Date();
   current_time = current_time.getTime()
   document.getElementById("id_currentTime").setAttribute("value", current_time)
}

window.onload = record_current_time;

并将下一个代码放在我的 html 中:

  <input type="hidden" name="currentTime" id="id_currentTime"/>

在这两种情况下,我的数据库中都没有任何内容。

谁能帮帮我

【问题讨论】:

  • 你的模型中是否定义了相应的字段?您是否尝试过通过页面模板(即{% formfield player.currentTime %})而不是硬编码来生成隐藏输入?表单是如何提交的?

标签: javascript html otree


【解决方案1】:

您的第一个代码不起作用有两个原因:

  • 您使用的 ID 不存在:“demo”
  • 如果您将 .innerHTML 替换为 .value,您的代码将起作用。见讨论here

关于第二次尝试,此命令将起作用:

window.onload = function() {
    record_current_time();
}

另一种适用于页面顶部脚本的可能性是:

$(document).ready(function(){
        function record_current_time(){
           var current_time = new Date();
           current_time = current_time.getTime();
           document.getElementById('id_currentTime').value = current_time;
        }

        record_current_time();
});

但是,您也可以将脚本放在页面底部。然后在您执行脚本时将加载所有元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2016-08-27
    • 2018-07-04
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多