示例 HTML 页面:
<div>
<ul>
<li> 1 </li>
<li> 2 </li>
</ul>
</div>
然后在ajax请求中我得到
<div>
<ul>
<li> 1 </li>
<li> 2 </li>
<li> 3 </li>
</ul>
</div>
是否可以更新第一个而不替换它?在那个特定的例子中,它应该只将一个列表项附加到 UL。
但是,如果我不知道 HTML 代码的外观,我如何确定是否需要添加、删除某些内容?
最佳答案
你的html代码需要这样
<div>
<ul id="retrivingList">
<li id="1"> 1 </li>
<li id="2"> 2 </li>
</ul>
</div>
你的SQL查询
$response["ids"] = array();
$response["list"] = array();
consider you need student roll no's from student tabel to appear in drop down
$studentDetail = "SELECT * FROM `student` WHERE 1 LIMIT 10";
$studentDetailExe = mysql_query($studentDetail) or die ("Error :".mysql_error());
while($data = mysql_fetch_assoc($studentDetailExe)){
array_push($response["ids"],$data["rollNo"]);
array_push($response["list"],"<li>".$data["rollNo"]."</li>");
}
*rollNo is column name in student tabel
你的js代码
$.ajax({
url: "trialDataRetrival.php",
method: "POST",
})
.done(function(response) {
var details = jQuery.parseJSON(response);
$("ul#retrivingList").children("li").each(function(event){
if($.inArray($(this).attr('id'),details.ids) >= 0){
}else{
//$.inArray() gives the position of element in the array
$("ul#retrivingList").append(details.list[$.inArray($(this).val(),details.ids)]);
}
});
})
.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
alert("Request Failed");
}); });
关于javascript - 仅在需要时更新 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728400/