简体   繁体   English

通过Ajax从JSON数据设置HTML表单字段

[英]Set html form fields from json data via ajax

This function grabs json from the server as a response. 该函数从服务器获取json作为响应。 What I want to do is to set html form fields using this ajax function. 我想要做的是使用此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();
}

Sample html form: 样本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>

The goal can be achieved through the following code: 可以通过以下代码实现目标:

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();
}

Hope, this will help others. 希望这会帮助别人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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