Ajax 调用以通过单击按钮返回填充表单字段 django
Posted
技术标签:
【中文标题】Ajax 调用以通过单击按钮返回填充表单字段 django【英文标题】:Ajax call to populate form fields django from with a click button return 【发布时间】:2020-08-12 13:29:13 【问题描述】:我想填写我的 django 字段表单以返回单击按钮功能。这样做的原因是允许手动和单击按钮选项。点击按钮功能从串行连接的设备收集读数。我怎样才能为此目的使用 ajax 调用 - 感谢您的帮助。 a screen shot of my page
enter image description here
【问题讨论】:
【参考方案1】:var ReadingNumber = ["First_Reading", "Second_Reading", "Third_Reading", "Fourth_Reading"];
// First Reading button
//for (i = 0; i < ReadingNumber.length; i++)
$(function ()
// text=''
var button_id = '.Insert_'
button_id += ReadingNumber[0]
// console.log(button_id);
$(button_id).click(function ()
$.ajax(
url: '/output/get_reading/',
type: 'GET',
dataType: 'json',
success: function (data)
var field_id = ReadingNumber[0]
field_id += '_Field'
// console.log(field_id);
var elem = document.getElementById(field_id);
htmlString =' <input type=number step=any name="First_Reading" maxlength="200" required id="id_'
htmlString += ReadingNumber[0]
htmlString += '" value='
htmlString += data + '>'
// console.log(htmlString);
elem.innerHTML = htmlString
// console.log();
);
);
);
//
// Second Reading button
$(function ()
$(".Insert_Second_Reading").click(function ()
$.ajax(
url: '/output/get_reading/',
type: 'GET',
dataType: 'json',
success: function (data)
var elem = document.getElementById('Second_Reading_Field');
htmlString =' <input type=number step=any name="Second_Reading" maxlength="200" required id="id_Second_Reading" value ='
htmlString += data + '>'
// console.log(htmlString);
elem.innerHTML = htmlString
// console.log();
);
);
);
// Third Reading button
$(function ()
$(".Insert_Third_Reading").click(function ()
$.ajax(
url: '/output/get_reading/',
type: 'GET',
dataType: 'json',
success: function (data)
var elem = document.getElementById('Third_Reading_Field');
htmlString =' <input type=number step=any name="Third_Reading" maxlength="200" required id="id_Third_Reading" value ='
htmlString += data + '>'
// console.log(htmlString);
elem.innerHTML = htmlString
// console.log();
);
);
);
// Fourth Reading button
$(function ()
$(".Insert_Fourth_Reading").click(function ()
$.ajax(
url: '/output/get_reading/',
type: 'GET',
dataType: 'json',
success: function (data)
var elem = document.getElementById('Fourth_Reading_Field');
htmlString =' <input type=number step=any name="Fourth_Reading" maxlength="200" required id="id_Fourth_Reading" value ='
htmlString += data + '>'
// console.log(htmlString);
elem.innerHTML = htmlString
// console.log();
);
);
);
【讨论】:
这是我设法做到的。它可以工作,但我无法循环使用 - 而不是为每个按钮复制该功能:( 知道如何在循环中包含这种 ajax 调用吗?以上是关于Ajax 调用以通过单击按钮返回填充表单字段 django的主要内容,如果未能解决你的问题,请参考以下文章
如何通过包含表单数据但不单击提交按钮的 ajax 将视图模型发送到控制器