小编典典

使用Javascript解析HTML中的AJAX响应

ajax

我在使用Javascript的代码中使用AJAX调用。

function loadFacility(callback)
{
    //alert('In loadFacility');
    var xmlhttp;
    var keys=document.firstCallInformation.facilityselect.value;
    var urls="http://localhost:8080/webfdms/showFirstCallInformation.do?vitalsId=366";
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status == 200)
        {
             //var some=xmlhttp.responseXML.documentElement;
            var response = xmlhttp.responseText;
            console.log(response)
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET",urls,true);
    xmlhttp.send(null);
}
function loadFacilityCallback(response){
if(response != null){
    //alert(response);
    console.log(response);
    var div = document.createElement("div");
    div.innerHTML = response;
    document.getElementById("facilityselect").innerHTML = div.querySelectorAll("select#facilityselect");;
}

编辑: 我已经更新了我的回调函数。但是在这里,我收到了选择列表作为[对象节点列表]。现在如何在HTML中显示?

在回调函数中,我现在想以HTML格式接收响应,因此我想解析该HTML响应,以便进一步处理它。我正在使用普通的javascript来做到这一点。如何解析以HTML格式接收的Ajax响应?


阅读 246

收藏
2020-07-26

共1个答案

小编典典

创建一个DIV元素并将HTML放入其中innerHTML。那将解析它。

var div = document.createElement("div");
div.innerHTML = response;

现在,您可以处理它div,例如div.querySelector(".classname")。要获取所有<select>标签,请执行以下操作:

var selects = div.querySelectorAll("select");

要将其放入您的网页,您可以执行以下操作:

document.getElementById("facilityselect").innerHTML = div.querySelector("select#facilityselect").innerHTML
2020-07-26