简体   繁体   中英

Jquery ajax parse html from json response

I need select a div by id from html in json response.

In server side:

    ob_start();

    extract($this->validate($this->data));
    require("classes/View/". $this->view . ".phtml");

    $content = ob_get_contents();
    ob_end_clean();

    header('Content-type: application/json');

    echo json_encode(array(
        'messages' => $this->data["messages"],
        'content' => $content
));

and in client side:

    $.ajax({  
        type: "POST",  
        url: o.url ,
        dataType: "JSON",
        data: o.ajax_data,
        success: function(response) {
                    $("#mydiv").html($(response.content).find("#mydiv"));
        }
    });

Before, when I used HTML as dataType and I returned plain HTML as response, everything have been functional. I can't figure out the right solution even after hours of research. Can anybody help me please?

===UPDATE 1===

console.log(response.content) => {"messages":[],"content":"complete escaped html site here"}

You are placing #mydiv (placeholder element in response) into DOM placeholder #mydiv . What you are probably want to do is place content of #mydiv from response into placeholder.

Assuming your response.content is properly formed html code this should work:

var content = $(response.content).find("#mydiv").html(); // get html of #mydiv in response
$("#mydiv").html(content);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM