通过ajax从json数据设置html表单字段

时间:2014-01-27 13:36:24

标签: javascript html ajax json

此函数从服务器获取json作为响应。我想要做的是使用此ajax函数设置html表单字段。

function getProfile()
{
    var xmlhttp;
    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)
        {
                    //This is the json response
                    alert(xmlhttp.responseText);
            //Set html form fields, but how?
        }
    }
    xmlhttp.open("POST","http://localhost:8080/SampleApp/user/profile",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send();
}

示例html表单:

<html>
   ......//
   ......//
   <form id="1" name="1">
     FName:<input type="text" name="txt1" id="txt1">
     LName:<input type="text" name="txt2" id="txt2">
     .................//
     ..............//
   </form>
</html>

1 个答案:

答案 0 :(得分:0)

可以通过以下代码实现目标:

function getProfile()
{
var xmlhttp;
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 jsonVar=xmlhttp.responseText;
        obj = JSON && JSON.parse(jsonVar) || $.parseJSON(jsonVar);
        document.getElementById("txt1").value=obj.name;
        document.getElementById("txt2").value=obj.email;
        //keep on going
    }
}
xmlhttp.open("POST","http://localhost:8080/SampleApp/user/profile",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}

希望,这会有所帮助。