Home > Blockchain >  AJAX JSON How to detect a Boolean value and create conditions?
AJAX JSON How to detect a Boolean value and create conditions?

Time:01-26

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'.

enter image description here

CodePudding user response:

while this is something that front-end frameworks handle particularly well, a common convention would be to split your template HTML. For example:

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>";
    if (model.media) {
        //add img to template, could also check model.mediasrc != null
        temp  = "<img src=../static/"   model.mediasrc   ".png>"
    }
    temp  = "</div>";

    $("#display").append(temp);
}

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:

  "<b>"   model.user_id   "</b>"

becomes:

  `<b>${model.user_id}</b>`

CodePudding user response:

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 whether model.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:

function imgMarkup (model) {
  if (model.mediasrc) {
    return `<img src="${model.mediasrc}" />`     
  }
  return '';
}
for (var model of response.models_to_return) {
  const temp=`
    <div class='container darker'>
      <b>${model.user_id}</b>
      <p>${model.room}</p>
      <span class='time-left'>${model.datetime}</span>
      ${imgMarkup(model)}
    </div>`;
    $("#display").append(temp);
}
  • Related