JavaScript无法创建<li>:C#后端JSON无法渲染为页面列表问题
解决AJAX提交后无法生成列表的问题
问题根源及修复步骤:
- 表单默认提交导致页面刷新:submit类型按钮点击后会触发表单提交,页面刷新会清空刚添加的列表项,AJAX操作被中断。
- JSON字段不匹配:控制器返回的JSON字段是
name,但前端JS尝试读取response.SoftwareName,导致列表项内容为undefined。 - 无效DOM查找:Process Name输入框缺少
id="processName",JS中getElementById("processName")会抛出错误。 - jQuery AJAX回调错误:使用了不存在的
failure回调,正确的错误回调是error。
修正后的代码:
1. C#控制器(二选一)
要么修改返回的JSON字段名,与前端取值一致:
[HttpPost] public ActionResult SoftwareNameResults(ReportModel report) { list.Add(report); // 返回与前端匹配的SoftwareName字段 return Json(new { SoftwareName = report.SoftwareName }); }
或者保持控制器返回不变,前端修改为response.name(推荐前者,更直观)。
2. JavaScript代码
function getSoftwareNames(event) { // 阻止表单默认提交行为,避免页面刷新 event.preventDefault(); var name = document.getElementById("softwareName").value.trim(); // 空输入校验 if (!name) { alert("请输入软件名称"); return; } var stuff = { SoftwareName: name }; $.ajax({ type: "POST", url: "@Url.Action("SoftwareNameResults","Report")", dataType: "json", contentType: "application/json; charset=utf-8", data: JSON.stringify(stuff), success: function(response) { // 清空输入框 document.getElementById("softwareName").value = ""; document.getElementById("processName").value = ""; // 创建并添加列表项 var list = document.getElementById("softwareList"); var listItem = document.createElement("li"); listItem.textContent = response.SoftwareName; // 对应控制器返回的字段 list.appendChild(listItem); }, // 修正为jQuery官方的error回调 error: function(err) { alert("请求失败:" + (err.responseText || "未知错误")); } }); }
3. HTML代码
@model ProjectName.Web.Models.ReportModel <div class="row"> <div class="col-md-12 mt-3"> <div class="card"> <h5 class="card-header">Process Report</h5> <div class="card-body"> <div class="row"> <!-- 添加onsubmit阻止默认提交,或修改按钮类型为button --> <form onsubmit="return false;"> <div class="col"> <label class="card-text" style="display: inline-block;">Software Name (Add-/Remove Programs)</label> <input type="text" id="softwareName" class="input-group-sm mb-3" /> <!-- 使用button类型避免触发表单提交,同时传递event参数 --> <button type="button" onclick="getSoftwareNames(event)">Search</button> </div> <div class="col"> <label class="card-text" style="display: inline-block;">Process Name</label> <!-- 添加上缺失的id --> <input id="processName" class="input-group-sm mb-3" /> </div> </form> </div> <div class="row"> <div class="col-md-12 col-sm-4"> <label class="card-body">Software Name Results:</label> <ul id="softwareList"></ul> </div> <div class="col-sm-4"> <label class="card-body">Process Name Results:</label> <ul id="processList"></ul> </div> </div> </div> </div> </div> </div>
内容的提问来源于stack exchange,提问作者JWright92
相关产品推荐
相关产品推荐

