在(x.html)模板中单击图像时,我想检索img.id或img.alt数据。然后,检索到的数据将用于填充另一个模板(dashboard.html)。我唯一的问题是如何在“ onclick”事件上检索数据。将数据存储在某处后,我将能够根据该信息找出如何填充另一个模板。如果我要添加'dashboard.html'应该是实时统计信息显示板,您的答案是否会更改?
我已经有了以下工作的js,该js返回所点击图像的ID。例如,如何在views.py中使用该数据?
[{ url: 'url_1' }, { url: 'url_2' }, { url: '...' }]
在html(x.html)下方,我想在其中通过视图导入的每个图像上添加onclick函数。
function ImgDetails(img){
var name = img.src;
var id = img.id;
console.log(id);
}
这是我的views.py:
{% include 'navigation.html' %}
<div id="Content">
<div id="List-Content">
<!--- All_Test -->
{% for key, value_list in Drank.items %}
<div id ="Content-List">
<div id ="Title-Box">
<h1 class="hero_header">{{ key }}</h1>
</div>
{% for value in value_list %}
<div id ="Menu-Item">
<div id ="Menu-Item-Wrap">
<img style="margin: 0 auto;" id="{{ value }}" src="{{ value }}">
</div>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</body>
{% include 'footer.html' %}
答案 0 :(得分:1)
要检索数据,您将:
HTML:
<p id="malek" onclick="getAttribute(this)" >malek</p>
JS:
function getAttribute(elem){
//get an attribute value of the element
idElement = elem.getAttribute('id');//src or howerver you want
}
//then you should submit it with ajax request
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/YourRouteHere");//here you paste the route where u can receive data
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({src:idElement})); //And here ur data in Json Format
答案 1 :(得分:0)
我在不同的帖子中找到了解决方案。也感谢@Conan为我指出正确的方向。以下json代码对我有用:
function PostImageDetails(element) {
var imageSrc = element.src;
var imageId = element.id;
console.log(imageSrc);
console.log(imageId);
//String manipulate ID
imageId = imageId.split("/");
imageId = imageId[4];
imageId = imageId.split(".");
imageId = imageId[0];
imageId = imageId.replace(/[^a-zA-Z ]/g, "");
console.log(imageId);
//CREATE HTTP REQUEST
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/api/users/", true);
xmlhttp.setRequestHeader("X-CSRFTOKEN", getCookie('csrftoken')); //HTTP_X_CSRFTOKEN
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({'url':imageSrc, 'username': imageId}))
//GET THE RESPONSE FROM THE SERVER
xmlhttp.onload = function(){
var csrftoken = getCookie('csrftoken');
console.log(csrftoken);
console.log(xmlhttp.status);
console.log(xmlhttp.statusText);
console.log(xmlhttp.responseText);
console.log(xmlhttp);
};
}
//Create Cookie/Token
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}