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

JavaScript无法从JSON加载表格,求实现带行数据回填的数据库表格方案

Fixing JSON Table Loading & Implementing Row-Click Textbox Population

First, let's get your ASMX WebMethod sorted—it looks like your code was cut off, and returning data correctly is key here. Here's the corrected version to ensure it sends valid JSON to your frontend:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false, XmlSerializeString = false)]
public void CargarUsuarios() {
    var wcf = new wsDN.ServicioClient();
    var usuarioList = wcf.Listar_Usuario().Valor; // Assuming this is your list of user objects
    
    // Set response content type to JSON
    Context.Response.ContentType = "application/json";
    // Serialize the list to JSON (use Newtonsoft.Json or JavaScriptSerializer)
    Context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(usuarioList));
    Context.Response.End();
}

Note: If you don't have Newtonsoft.Json installed, grab it via NuGet, or replace the serialization line with new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(usuarioList).

Next, let's handle the frontend. We'll use jQuery (since it simplifies AJAX and DOM manipulation) to load data on page load, build the table, and add click handlers for populating text boxes.

1. HTML Setup

First, add the table container and text boxes to your page:

<!-- Table for User Data -->
<div>
    <table id="userTable" border="1" cellpadding="8">
        <thead>
            <tr>
                <th>User ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

<!-- Text Boxes to Populate -->
<div style="margin-top: 20px;">
    <label>Selected User ID:</label>
    <input type="text" id="txtUserId" readonly><br><br>
    
    <label>Selected User Name:</label>
    <input type="text" id="txtUserName"><br><br>
    
    <label>Selected User Email:</label>
    <input type="text" id="txtUserEmail">
</div>

2. JavaScript to Load Data & Add Functionality

Add this script (make sure jQuery is included in your page first):

$(document).ready(function() {
    // Fetch data from ASMX when the page loads
    $.ajax({
        type: "POST",
        url: "YourPage.asmx/CargarUsuarios", // Replace with your actual ASMX page path
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            // ASMX wraps JSON responses in a "d" object—extract the user list
            const users = response.d;
            const tableBody = $("#userTable tbody");
            
            // Clear any existing rows
            tableBody.empty();
            
            // Loop through each user and build table rows
            users.forEach(user => {
                const row = $("<tr>");
                
                // Add user data to columns (replace property names with your actual ones)
                row.append($("<td>").text(user.Id));
                row.append($("<td>").text(user.Nombre));
                row.append($("<td>").text(user.Correo));
                
                // Add a clickable "Select" link
                row.append($("<td>").html('<a href="#" class="select-btn">Select</a>'));
                
                // Store the full user object in the row for easy access later
                row.data("userData", user);
                
                tableBody.append(row);
            });
            
            // Add click handler to all "Select" links
            $(".select-btn").on("click", function(e) {
                e.preventDefault();
                
                // Get the user data from the clicked row
                const selectedUser = $(this).closest("tr").data("userData");
                
                // Populate the text boxes with the selected user's data
                $("#txtUserId").val(selectedUser.Id);
                $("#txtUserName").val(selectedUser.Nombre);
                $("#txtUserEmail").val(selectedUser.Correo);
            });
        },
        error: function(xhr, status, err) {
            // Handle errors (check browser console for details)
            console.error("Failed to load users:", err);
            alert("Oops! Couldn't load user data. Check the console for more info.");
        }
    });
});

Important Things to Adjust:

  • Property Names: Replace user.Id, user.Nombre, user.Correo with the exact property names from your Listar_Usuario response.
  • ASMX Path: Update url: "YourPage.asmx/CargarUsuarios" to match your actual ASMX file path.
  • Error Debugging: If the AJAX call fails, open your browser's dev tools (F12) → Network tab to check the response from the ASMX method—this will tell you if the data is being sent correctly.

Troubleshooting Common Issues:

  • JSON Serialization Errors: Make sure Listar_Usuario().Valor returns a serializable object (like a list of simple POCOs, not a complex type with circular references).
  • ASMX "d" Property: Don't forget that ASMX wraps responses in response.d—if you skip this, you'll get undefined data.
  • Click Handler Not Working: Using on("click") ensures the handler works for dynamically added rows (since the links are created after the AJAX call).

内容的提问来源于stack exchange,提问作者Errol Chaves Moya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:56:40