'Pass data to sling model

Is it possible to pass a string or data that is retrieved in an Ajax call to sightly html? I have a 3rd party response in Ajax but I am trying to make the html look prettier by not using script tags. Hence I am planning to write pojos. But the call to the 3rd party will be an Ajax call. Is there a way to bind the Ajax response to sightly html ?



Solution 1:[1]

You can try to call the ajax inside the JavaScript Use API.

<sly data-sly use.data1='getAjaxResponse.js'/>

Then pass the response to the model

<sly data-sly-use.sampleModel="${'com.project.SampleModel' @data1=data1}"/>

The below code JavaScript is not synchronous, so that needs to be handled separately

getAjaxResponse.js

use(function() {
    let result;
    $.ajax({url: "/path/to/ajax/", success: function(response){
        result = response;
    }});
    return result;
}

SampleModel.java

@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SampleModel{

    @Inject
    private String data1;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akshay Rathnavas