从ajax响应加载html内容


Load html content from ajax response

我正在openart中创建一个应用程序,其中控制器以json形式返回输出。如果我做$('.my-div').html(json['output']),那么它工作得很好。但是我如何从该响应中过滤特定的divtable,并仅将过滤的html放在我的div中。我知道$('.my-div').load('index.php?route=mymodule/subpage' .my-div > * );,但它不起作用,因为我的控制器被创建为返回输出而不是生成。

控制器返回的是

$json['output'] = $this->load->view('default/template/mymodule/mytemplate.tpl', $data);

编辑

我得到的回应是json['output'] = '<div>......</div><table class="myclass"></table>';

我想在我的div中只加载myclass。那么我怎么能从响应中只过滤myclass table呢?我试过滤镜,但它给我错误

就像Raghubendra说的,最好只保留html你需要在.tpl文件,但如果你不能这样做,无论出于什么原因,你可以尝试过滤它在服务器端使用xPath[这不是最快的方式,但它是一个干净的方式来获得结果]。我认为你可以这样做:

$output = $this->load->view('default/template/mymodule/mytemplate.tpl', $data);
$dom = new DOMDocument();
@$dom->loadHTML($output); // @ is to suppress all warnings related to the fact that html is not a proper dom document
$xpath = new DOMXPath($dom);
$match = $xpath->query('//table[@class="myclass"]');
/* $match is not an array, it implements 'Traversable', you can't access your <table> node using $match[0],
 you need a foreach that will only loop once if you have one <table class="myclass"> element */
foreach($match as $table) {
    $json['output'] = $table->ownerDocument->saveHTML($table); // saveHTML allows you to get the output in an HTML string
} 

N。B:请注意,如果您有多个<table class="myclass">,您需要更改此代码,我建议使用iterator_to_array($match);将节点列表转换为数组,以便您可以使用$match[0]...访问它并避免foreach

如果你只想在你的div html的一部分,那么你为什么要呈现整个tpl文件。为什么不把你不想用的html代码删掉呢?

假设你的mytemplate。tpl已

<div>
---------
--------
</div>
<table class="myclass"></table>
<div>
---------
--------
</div>

那么为什么不只保留表代码并删除所有其他代码,因为您在呈现tpl文件时不使用它