My webpage is receiving through AJAX GET requests Arrays with strings, and a Boolean.
The objects within the array are displayed subsequently to shape a chat app, the received array represents messages to display in a chatbox. However, some of the messages have media in them.
Therefore, to recognize such message with image source in them, I added a Boolean Value (media=True : There is an image source).
With my current code, all arrays are testing their source in an empty <img src"">
which creates a real mess on the chat box with unknown images. I need to be able to generate with JS an HTML image when an Object has a media = True with a source of ‘mediasrc’.
HTML:
<div id="display"></div>
JS:
<script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: "/checkview",
success: function go(response) {
console.log(response);
$("#display").empty();
for (var model of response.models_to_return) {
var temp = "<div class='container darker'><b>" +
model.user_id + "</b><p>" +
model.room + "</p><span class='time-left'>" +
model.datetime + "</span><img src=../static/" +
model.mediasrc + ".png></div>";
$("#display").append(temp);
}
},
error: function(response) {
//alert('An error occured')
}
});
}, 1000);
})
</script>
By the way, this code works fine, but it’s literally brute forcing all messages trying to fill an img:
2
Answers
Not 100% sure I understand the question, but you could create a utility function that takes the model and returns either the
<img>
markup or an empty string depending on whethermodel.mediasrc
is present (or whatever condition is appropriate for your needs).This probably isn’t the exact implementation you need, but it demonstrates the pattern:
while this is something that front-end frameworks handle particularly well, a common convention would be to split your template HTML. For example:
If you want to write code up to the latest conventions, replace double quotes with back ticks, and reference variables with ${var_name}.
For example:
becomes: