You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery处理经JSON编码的AJAX动态表单返回结果

问题修复方案

故障根因

  • PHP端存在无效语法,提前输出HTML内容导致JSON结构被破坏,前端无法正常解析
  • 前端AJAX回调中错误将JSON对象当作HTML字符串进行DOM筛选,逻辑不成立
  • 未拦截PHP意外输出(报错、前置空格换行等),会直接导致JSON格式失效

修正后的PHP代码(getting_result.php)

<?php
require_once('include/form.class.php');
// 拦截错误输出,清空缓冲区避免意外内容混入JSON
error_reporting(0);
ob_start();

// 增加参数校验避免未定义报错
$rowid = $_POST['rowid'] ?? 0;
$getjson_form = getJsonForm($rowid);
$form = new Form(['file' => $getjson_form[0]['json_form_name']]);

// 原代码中的ouput行是无效PHP语法,如需要外层div请拼接至表单内容中
// 示例:$form_wrap = '<div class="form-row" id="form_output_row"><div class="form-group col-md-6">' . $form->show() . '</div></div>';
$get_form = $form->show();

$total_output = [
    "json_form_name" => $get_form
];

// 清空所有前置意外输出,返回标准JSON
ob_end_clean();
echo json_encode($total_output, JSON_FORCE_OBJECT);
exit;
?>

修正后的前端AJAX代码

$.ajax({
    type: "POST",
    url: "getting_result.php",
    data: { rowid: id },
    dataType: "json",
    cache: false,
    success: function (data) {
        console.log(data.json_form_name);
        // 从JSON的指定字段取HTML字符串再做DOM筛选
        var find_form = $(data.json_form_name).filter('#form_output_row');
        console.log(find_form);
        $("#jsonformname").html(data.json_form_name);
    },
    // 新增错误回调方便定位解析问题
    error: function (xhr, error) {
        console.log('JSON解析失败,原始返回内容:', xhr.responseText);
    }
});

其他注意事项

  • 动态插入的表单如果需要绑定事件,建议使用事件委托绑定到页面固定存在的父级节点上,避免插入的元素无法触发对应事件
  • 确保getJsonForm、Form->show()方法内部没有直接echo输出内容,所有返回内容必须通过return赋值给变量,否则会提前输出破坏JSON结构

内容的提问来源于stack exchange,提问作者mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:27:03