How to use AJAX in an iframe?

1

To contextualize:

I'm trying to make only a part of my HTML page updated every 5 seconds. For this, I'm using AJAX. In the middle of development, I encountered a problem of not being able to return the object and my view at the same time, since both were accessed by the same URL ("/ log ").

So I created a frame

<iframe id="logIframe" src='about:blank' width="900" height="500"></iframe>

So that I keep my view on the page (around the frame) and the object being displayed inside the frame. My problem is that, my object is returning empty and I do not know why. If I return the object, instead of the view, the object returns correctly:

Otherwise:

MypostthatiscalledbytheAJAXfunction:

//"log"
@RequestMapping(value = "/logTest", method = RequestMethod.POST)
@ResponseBody
public String iframeLogPost(@Valid Log log, BindingResult bindingResult, Map<String, Object> model) {
    if (log.getInitLine() == 0 && log.getFinalLine() == 0) {
        try {
            fileNumberLines(log);
            log.setContent(getLogContentByRange(0, log.getInitLine(), log.getFinalLine(), logsDir + "/" + log.getFilename()));
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    } else {
        log.setContent(getLogContentByRange(0, log.getInitLine(), log.getFinalLine(), logsDir + "/" + log.getFilename()));
    }

    // View:
    //model.put("path", logsDir);
    //model.put("log", log);
    //model.put("currentPage", "logs");
    //model.put("root", root);

    return log.getContent();
}

My AJAX function:

function reload() {

    var ifrm = document.getElementById('logIframe');
    ifrm = ifrm.contentWindow || ifrm.contentDocument.document
            || ifrm.contentDocument;

    $.ajax({
        type : 'post',
        url : '/logTest',
        success : function(data) {

            console.log(data);
            ifrm.document.open();
            ifrm.document.write(data); // Escreve no iframe
            ifrm.document.close();
        }
    });
}

Doubts:   What am I doing wrong?

    
asked by anonymous 14.08.2018 / 18:28

2 answers

0

Hello @David Caina, let's consider that you have 2files:

In one vc you put a div to receive the iframe, and put the ajax with the following code in success:

html:
div class=".recept_iframe" /div

no ajax:

setInterval(function(){
    $(".recept_iframe").load("pasta/iframe.php");
}, 5000);//com o setInterval, vai carregar a cada 5segundos 
  • In the other file you put the iframe.
14.08.2018 / 18:57
0

I think you should note the Log parameter with @RequestBody:

@ResponseBody
 public String iframeLogPost(@Valid @RequestBody Log log, BindingResult bindingResult,

And the fields of this class should have the names and types equal to those represented in the JSON passed in the post or map which class field represents that JSON field.

    
14.08.2018 / 22:52