开发者

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 m开发者_高级运维ore 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:

  • How to use Servlets and Ajax?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜