Pass data to sling model

724 views Asked by At

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 ?

1

There are 1 answers

0
Akshay Rathnavas On

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;
}