问题
I'm using the newest Version of Wordpress. On a private page I've created my very first filter field on a dropdown. The filter options are the different years, queried from a custom table. No issues here.
Changing the filter field triggers an AJAX-call to the backend using jQuery. The callbackfunction on the php-backend then runs 2 queries on the database: 1. Getting the calendar weeks possessing one or more entry from the custom table 2. Getting the entries per week
The problem: The second query runs for every result of the first query. Therefore it is nested in a loop. But i need to display the first value as well.
What I've tried: Joining all the ouput of the queries into a php-string including the HTML-wrapper-classes for each entry, then using the string as the AJAX response. But this attempt includes nonprintables (\n or \t). I need to keep the output readable to edit it. It doesn't actually get formatted like html.
My questions:
- Should the AJAX response be formatted as HTML in the callback function? And how can it be displayed in the frontend?
- Should the AJAX response simply be a JSON object? And how can the entries of the second query get mapped to the ones from first query in the frontend?
Here's the current code of the very basic ajax call:
var filter = $('#filter');
$.ajax({
url:filter.attr('action'), // ajax
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
dataType:"html",
success:function(data){
$('#json-response').html(data);
//TBD: Properly display data of response
}
});
The expected pseudo HTML-output would look something like this:
<div class="week-container">
<div class="week-header">
CALENDAR WEEK 1 <-- Result from first query
</div>
<div class="week-entry-0">01.01.2020, ... more data</div> <-- Result from second query
<div class="week-entry-1">03.01.2020, ... more data</div> <-- Another result from second query
</div>
<div class="week-container">
<div class="week-header">
CALENDAR WEEK N
</div>
<div class="week-entry-i">data</div>
<div class="week-entry-i+1">data</div>
</div>
and so on...
回答1:
This is a bad practice that Ajax responses have HTML format. just send data in JSON format from server to client. so it will be standard.
来源:https://stackoverflow.com/questions/61828984/format-ajax-response-into-html