从JSON提取数据在SweetAlert弹窗展示时遇到问题求助
Fixing Your JSON-to-SweetAlert Display Issue
Let's walk through the problems in your code and get that popup working correctly:
Key Issues to Address
- Broken Function & AJAX Structure: Your
check_values_chbxfunction isn't properly closed, and thedone()callback is misplaced. It looks like you're missing the actual AJAX request wrapper around that callback. - Incorrect Loop Bound: You're looping against
response.length, but you need to iterate overresponse[0]['personas']instead—this will cause errors if the lengths don't match, or fail to grab all participant names. - Line Breaks Not Working in SweetAlert: Plain
\nwon't render as line breaks in SweetAlert's default text mode; you need to use HTML<br>tags and enable HTML rendering. - Incomplete SweetAlert Configuration: The
buttons: true...line is truncated—you need a valid, complete configuration here.
Corrected Code
function check_values_chbx() { var pre_insc = []; // Add your full AJAX request here (replace with your actual endpoint) $.ajax({ url: "/your-data-endpoint", method: "GET" }).done(function(response) { // Guard clause to avoid errors if data structure is unexpected if (!response[0] || !Array.isArray(response[0].personas)) { swal("Oops", "No se encontraron participantes válidos", "warning"); return; } // Loop through the personas array correctly for (let i = 0; i < response[0].personas.length; i++) { const persona = response[0].personas[i]; // Use template strings for cleaner concatenation pre_insc.push(`${persona.name} ${persona.ap_pat} ${persona.ap_mat}`); } // Render SweetAlert with proper line breaks swal({ title: "Detalles de inscripcion", // Use html instead of text to render line breaks html: `Participantes que quedaran inscritos: <br><br>${pre_insc.join('<br>')}<br><br>Categoria:`, // Complete button configuration (customize as needed) buttons: { confirm: "Confirmar", cancel: "Cancelar" } }); }).fail(function(err) { // Handle AJAX request failures gracefully swal("Error", "No se pudo cargar los datos de inscripción", "error"); }); }
What Changed & Why
- Fixed AJAX Structure: Added the full
$.ajax()wrapper to ensure thedone()callback is attached correctly, and added afail()handler to catch request errors. - Corrected Loop: Now loops over
response[0].personas.lengthto ensure we get every participant, not just as many as there are items in the top-levelresponsearray. - Better String Handling: Used template strings for clearer name concatenation, and
Array.push()instead of direct index assignment (more reliable). - Working Line Breaks: Switched to the
htmlparameter in SweetAlert and used<br>tags to make line breaks visible. - Error Safety: Added a guard clause to check that the expected data structure exists, preventing unexpected crashes if the API response is different than expected.
内容的提问来源于stack exchange,提问作者Mexa Fireg
相关产品推荐
相关产品推荐

