简体   繁体   中英

Populating dropdown list in JSP using AJAX response

Below is the code which I implemented to get dropdown list items by Ajax in JSP:

if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
    var data = xmlHttp.responseText.split("~");
    alert(data);

    var listb = document.getElementById("listbox");
    var textValue;
    var optionItem;

    for ( var count = 0; count < data.length; count++) {
        textValue = (data[count]);
        optionItem = new Option(textValue, textValue, false, false);
        listb.options[listb.length] = optionItem;
    }
}

But I am getting some more text with first item:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

But I am not getting from where it is coming. Where does it come from and how can I solve it?

You seem to be using JSP instead of Servlet to return the ajax response. Perhaps you've just put that doctype in top of that JSP yourself, or some framework which you're using is adding it implicitly on JSP responses.

You shouldn't be using JSP for Ajax responses. Use a servlet instead. Create a servlet which writes the desired data to the response and let Ajax call the URL of that servlet instead. Also consider using JSON as response body instead of a String with ~ as delimiter. JSON is less error prone and much easier to parse in JavaScript.

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM