将AJAX响应格式设置为HTML [英] Format AJAX-Response into HTML

查看:86
本文介绍了将AJAX响应格式设置为HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用最新版本的Wordpress.在私人页面上,我在下拉列表中创建了我的第一个过滤器字段.过滤器选项是从自定义表中查询的不同年份.这里没有问题.

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.

更改filter字段会触发使用jQuery后端的AJAX调用.然后,在php-backend上的callbackfunction在数据库上运行2个查询:1.从定制表中获取拥有一个或多个条目的日历周2.每周获取条目

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.

我尝试过的操作:将所有查询的输出连接到一个php字符串中,包括每个条目的HTML-wrapper-classs,然后使用该字符串作为AJAX响应.但是,此尝试包括不可打印的内容(\ n或\ t).我需要保持输出可读以对其进行编辑.它实际上并没有像html那样格式化.

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.

我的问题:

  1. 应在回调中将AJAX响应格式化为HTML功能?以及如何在前端显示它?
  2. AJAX响应应该只是一个JSON对象吗?以及如何将第二个查询的条目映射到第一个查询的条目在前端?

这是最基本的ajax调用的当前代码:

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

预期的伪HTML输出如下所示:

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...

推荐答案

这是Ajax响应具有HTML格式的不良做法.只需将JSON格式的数据从服务器发送到客户端即可.所以这将是标准的.

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.

这篇关于将AJAX响应格式设置为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆