Jquery ajax解析来自json响应的html

时间:2022-10-09 11:33:06

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

我需要在json响应中从html中选择一个id by div。

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?

之前,当我使用HTML作为dataType并且我将纯HTML作为响应返回时,一切都已正常运行。经过数小时的研究,我无法找到正确的解决方案。有人可以帮帮我吗?

===UPDATE 1===

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

console.log(response.content)=> {“messages”:[],“content”:“在这里完成转义的html网站”}

1 个解决方案

#1


0  

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.

您将#mydiv(占位符元素作为响应)放入DOM占位符#mydiv中。您可能想要做的是将#mydiv的内容从响应放入占位符。

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

假设你的response.content是正确形成的html代码,这应该工作:

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

#1


0  

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.

您将#mydiv(占位符元素作为响应)放入DOM占位符#mydiv中。您可能想要做的是将#mydiv的内容从响应放入占位符。

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

假设你的response.content是正确形成的html代码,这应该工作:

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