在PHP Ajax的帖子,如何获得数组响应多个html元素与一个单一的Ajax调用


In PHP Ajax post, how to get array responses to multiple html elements with a single ajax call

查看页面

<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);