我有一个变量中的数据需要在Django中的views.py中传递。
代码:
index.html
<table class="table table-striped table-dark" cellspacing="0">
<thead class="bg-info">
<tr>
<th>Company's Symbol</th>
<th>Current Price</th>
<th>View Current chart</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for a,b in stocks %}
<tr>
<th scope="row" class="comp_name">{{ a }}</th>
<td>{{ b }}</td>
<td>
<button class="btn graph-btn">View Graph</button>
</td>
<td>
<button class="btn predict-btn">Predict Closing Price</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
当我点击.graph-btn
时,它将从.comp_name
获取数据。(下面是代码):工作正常
<script>
$(".graph-btn").click(function() {
var $row = $(this).closest("tr");
var $text = $row.find(".comp_name").text();
});
</script>
所以这里的text
中的数据我想在views.py中传递。
您应该使用ajax请求:
$.ajax({
type: 'POST',
url: 'YOUR VIEW URL',
data: {'row': row, 'text': text},
success: function (data){
DO SOMETHING HERE if VIEW has no errors
})
在你看来:
row = request.POST.get('row')
text = request.POST.get('text')
此外,您还应该关心crsf-token。 文件编制
您可以post
itget
it或将其作为变量放在url
中。 下面是一种post方法:
使用jQuery
:
$.ajax({
url : "/URL/to/view",
type : "POST", // or GET depends on you
data : { text: $text },
async: false,
// handle a successful response
success : function(json) {
// some code to do with response
}
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
在您的视图中,您可以以json的形式获取数据,并返回josn作为响应
import json
def my_view(request):
if request.method == 'POST':
response_data = {} // to return something as json response
text = request.POST['text']
...
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)