怎么用json把后端的数据传到前端html界面显示,javascript要怎么写?

charles_su
  • 42

//后端代码

public JsonResult SendData()
    {
        return Json( new {username="刘伟",teacherid="2432012522" });
    }
    

//前端代码

<div class="box5" style="position:relative;">
    <!-- 背景图的div -->
    <img style="position:absolute;margin-left: 5%;margin-top: 9%" src="~/Content/themes/portrait.png" width=28% height=50% />
    <img src="~/Content/themes/background.jpg" width=100% height=100% />
    <div class="FONT4" style="position:absolute; z-index:2; top:15px">姓名:刘伟</div>
    //怎么把这个“刘伟”替换成动态的,由后端发送的?
    <div class="FONT4" style="position:absolute; z-index:2; top:100px">教工号:2432012522</div>
    //怎么把这个“2432012522”替换成动态的,由后端发送的?
</div>
回复
阅读 6.6k
2 个回答

ajax请求这个Action,请求成功后,返回的数据渲染到这个div内容就行了

<div class="box5" style="position:relative;">
    <!-- 背景图的div -->
    <img style="position:absolute;margin-left: 5%;margin-top: 9%" src="~/Content/themes/portrait.png" width=28% height=50% />
    <img src="~/Content/themes/background.jpg" width=100% height=100% />
    <div class="FONT4" style="position:absolute; z-index:2; top:15px" id="username">姓名:刘伟</div>
    //添加id="username"
    <div class="FONT4" style="position:absolute; z-index:2; top:100px" id="teacherid">教工号:2432012522</div>
    //添加id="teacherid"
</div>
//使用JS
<script type="text/javascript>
    var xhr = new XMLHttpRequest();
    xhr.open("get","url",true); //url改成自己的请求地址
    xhr.send();
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
        var data = JSON.parse(xhr.responseText);
        document.getElementById("username").value = "姓名:" + data.username;
        document.getElementById("teacherid").value = "教工号:" + data.teacherid;
        }
    }
</script>
//使用jQuery
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript>
    $.get("url",function(result){
        var data = JSON.parse(result);
        $("#username").val("姓名:" + data.username);
        $("#teacherid").val("教工号:" + data.teacherid);
    })
</script>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进