【发布时间】:2017-11-16 03:22:22
【问题描述】:
我有多个输入标签,我的任务是收集用户输入的值并将其发送回服务器。我使用 Django 作为我的框架。我成功地将数据发送到客户端(javascript)。 要将数据从 javascript 函数返回到我的 python 函数,我使用了 XMLHttpRequest。 我在下面添加了我的代码:
<html>
<head>
<style>label{ text-align:center; width:250px; color:blue; display:inline-block}</style>
<script type="text/javascript" src="'+url_read+'"></script>
<script>
function submit_this()
{
var i,j;var arr=[];
for(i=0; i<Hello.length; i++)
{
arr[i]=[];
for(j=0;j<Hello[i].length; j++)
{
arr[i].push(document.getElementById(Hello[i][j]).value);
}
}
alert(document.getElementById(Hello[1][0]).value);
xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open('POST', '/button_click',true);
xmlHttpReq.send('w=' + encodeURI(arr));
}
</script>
</head>
<body>
<center>
<button id="submit_button" onclick="submit_this();" value="Submit">Submit</button>
</center>
</body>
</html>
以上代码存储在一个名为 html_string 的字符串中。 Hello 是从由变量 url_read 表示的文件中读取的 json 对象。它是使用 Python 转储的。 计划是使用 HttpResponse 发送 html_string 并作为回报呈现 html 页面。
我知道我需要在views.py 中的一个类中创建一个POST 函数。但无法理解如何解决这个问题。
我必须以某种方式将名为 arr 的 javascript 数据结构发送回服务器端。主要的疑问是我可以将我的代码放在哪里可以读取 javascript 函数发布的值。 一旦按下提交按钮,我想导航到一个新页面,并且在 Django 中,每个 url 都有一个与之关联的新函数(在 views.py 中)。我应该把它放在里面吗?
【问题讨论】:
-
请格式化您的代码。
-
js 中的错字。更改为
xmlHttpReq.open('POST', '/button_click',true); -
代码中的
Hello是什么。它是在其他地方声明的吗?只是想知道这是否是 js 中的关键字或等...? -
我忘了指出,Hello是我通过python传递的一个json对象。我将数据结构转换为 json 对象,然后转储到由变量 url_read 表示的文件中。 javascript函数读取相同的文件作为获取json对象(Hello)的源。Hello包含输入元素的ID,我使用javascript函数getElementById获取用户输入的值@Haranadh
标签: javascript python html django