尝试从JavaScript发送值到Python服务器

3

我有多个输入标签,我的任务是收集用户输入的值并将其发送回服务器。我正在使用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中)相关联。我应该把它放在那里吗?

1
请格式化您的代码。 - Ravi
你的JS中有一个错别字。请更改为xmlHttpReq.open('POST', '/button_click',true); - vinoth h
你的代码中 Hello 是什么?它在其他地方声明了吗?我只是想知道这是否是 JavaScript 或其他语言中的关键字...? - Hara
我忘了指出,Hello是我通过Python传递的JSON对象。我将数据结构转换为JSON对象,然后将其转储到由变量url_read表示的文件中。同一个文件被JavaScript函数读取作为源以获取JSON对象(Hello)。Hello包含输入元素的ID,我使用JavaScript函数getElementById来获取用户输入的值。@Haranadh - jyotirmaya ojha
1个回答

0
这里有一个例子,我使用JS向(Django)Python服务器发送值,并接收渲染的HTML模板。 我使用带有id #Nearby的ul标签来在HTML中加载HTML。 Ajax成功从Django视图返回通过URL端点'/getGopoints/'渲染的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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接