【问题标题】:Trying to send value from javascript to python server试图将值从 javascript 发送到 python 服务器
【发布时间】: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


【解决方案1】:

这是一个示例,我使用 JS 向 (Django)python 服务器发送值,并接收 html 呈现的模板。 我正在使用带有 id #Nearby 的 ul 标记在 html 中加载 html。 Ajax 成功是从通过 url 端点 '/getGopoints/' 呈现的 django 视图返回 html

template.html

<div class="row">
    <div>
        <ul id="Nearby">

        </ul>
    </div>  
</div>

 <script>
 $(document).ready(function(){
          $('#dataTables-example1').DataTable({
                    responsive: true
            });
          getLocation();
    });
 function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } 
    }


function showPosition(position) {
        $.ajax({
                url : '/getGopoints/', // the endpoint
                type : 'GET', // http method
                data : { 'lat' : position.coords.latitude,
                         'lon' : position.coords.longitude,
                        'csrfmiddlewaretoken': '{{csrf_token}}'
                 }, // data sent with the post request

                // handle a successful response
                success : function(data) {
                  $('#Nearby').html(data);  
                },
                dataType: 'html'

        });
    }
</script>

urls.py

 url(r'^getGopoints/$',views.getGopoints, name='getGopoints'),

views.py

def getGopoints(request):
    lat = str(request.GET['lat'])
    lon = str(request.GET['lon'])
    pnt=fromstr('POINT(%s %s)' %(lon,lat))
    with_in_distance = 20
    go_points = GoPoint.objects.filter(point__distance_lte=(pnt, D(km=with_in_distance)))
    context = RequestContext(request,
        {'go_points':go_points,
        'with_in_distance':with_in_distance,
        })
    return render_to_response('nearby.html',
                             context_instance=context)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-19
    • 2012-12-10
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多