如何通过AJAX动态生成指定结构的HTML事件列表?
Solution: Populate Dynamic Event List via AJAX
Great job getting your AJAX framework set up—you're almost there! The key part you're missing is constructing each list item string inside the $.each loop and appending it to your list variable. Here's how to modify your success function to match the target HTML structure:
Modified JavaScript Code
function GetList() { $.ajax({ async: false, type: "POST", contentType: "application/json; charset=utf-8", url: "ExampleList.aspx/GetList", dataType: "json", success: function (data, textStatus) { if (textStatus == "success") { var datos = jQuery.parseJSON(data.d); $("#EventList").html(''); // Start with the calendar-menu ul (matches your target structure) var list = '<ul class="calendar-menu">'; $.each(datos, function (i, v) { // Build each event li using data from your response object // Replace v.day, v.month, v.time, v.description with your actual data properties! list += ` <li> <time class="anthracite"><b>${v.day}</b> ${v.month}</time> <small class="green">${v.time}</small> ${v.description} </li> `; // Add line break between items (skip for the last item) if (i !== datos.length - 1) { list += '<br />'; } }); list += '</ul>'; $("#EventList").append(list); } }, error: function (request, status, error) { alert(jQuery.parseJSON(request.responseText).Message); } }); }
Key Notes:
- Data Property Names: I used
v.day,v.month,v.time, andv.descriptionas placeholders. You'll need to replace these with the actual property names from yourdatosobjects (e.g., if your response haseventDayandeventMonth, adjust accordingly). - Template Literals: I used ES6 template literals (backticks
`) for cleaner, more readable string construction. If you need to support older browsers, switch to string concatenation with+instead:list += '<li>' + '<time class="anthracite"><b>' + v.day + '</b> ' + v.month + '</time>' + '<small class="green">' + v.time + '</small>' + ' ' + v.description + '</li>'; - Line Breaks: The
<br />between items is included as per your target structure, but for better practice, consider using CSS margins on thelielements instead of hard-coded line breaks.
This will dynamically generate the exact HTML structure you're targeting, populating each event's details from your database response.
内容的提问来源于stack exchange,提问作者Nick Roberts
相关产品推荐
相关产品推荐

