查看页面
<button id = 'compare_button'>Compare</button>
<div id="sourceResponse"></div>
<div id="destResponse"></div>
<div id="missingResponse"></div>
JS
$(document).ready(function(){
$('#compare_button').click(function(event){
$.ajax({
type: 'POST',
url: 'compare.php',
dataType: 'json'
})
.done(function(response){
...
$("#sourceResponse").html(some-response);
$("#destResponse").html(some-response);
$("#missingResponse").html(some-response);
});
});
Compare.php
....
//converting arrays to json
echo json_encode($source_files);
echo json_encode($dest_files);
echo json_encode($missing_files);
我如何处理上面的json响应,以便在这3个html元素中显示各自的数据?
构建一个包含响应的数组,json_encode
并在响应
$output = array(
'source' => $source_files,
'dest' => $dest_files,
'missing' => $missing_files
);
echo json_encode($output);
在你的javascript中,像这样使用:
.done(function(response){
...
$("#sourceResponse").html(response.source);
$("#destResponse").html(response.dest);
$("#missingResponse").html(response.missing);
});
编辑:
在
done
处理程序
中// replace this
// $("#sourceResponse").html(response.source);
// with the following
$.each(response.source, function(key,value) {
console.log(key+"-"+value); // use this to check the object
// assuming the text you want is directly in the value you can use this
$("#sourceResponse").append('<code>'+value+'</code></br>');
})
基本上,我们正在迭代response.source
对象成员并构造<code>string</code></br>
并将它们附加到div
中,而不是直接推入对象的内容。
这是最短的路径:
echo json_encode([
"sourcefiles" => $source_files,
"destfiles" => $dest_files,
"missingfiles" => $missing_files
]);
console.log(response.sourceFiles);
console.log(response.destFiles);
console.log(response.missingFiles);