简体   繁体   English

如何使用 html 从属性文件中读取值

[英]How to read values from properties file with html

Below is my html snippet下面是我的html片段

First name:
<input type = "text" >
Last name:
<input type = "text">

Instead of hard coding the field values (First name,Last name) in the html I want to read them from a property file is this possible just with html.please suggest me a way to do it.而不是硬编码html中的字段值(名字,姓氏),我想从属性文件中读取它们,这可能只是使用html。请建议我一种方法。

You can read a file using ajax(XMLHttpReqeust).您可以使用 ajax(XMLHttpReqeust) 读取文件。

with no plugins:没有插件:

First name:
<input id="first_name" type="text">
Last name:
<input id="last_name" type="text">
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    var data = xmlhttp.responseText; // use JSON.parse if properties file is formatted as json
    document.getElementById('first_name').value = data; // use like this
    }
  }
xmlhttp.open("GET", "properties.txt", true);
xmlhttp.send();
</script>

Just put a file in the same folder as the html and load it with JQuery ajax:只需将文件放在与 html 相同的文件夹中并使用 JQuery ajax 加载它:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<input type="text" id="name" />
<input type="text" id="last_name" />
<script>
$(function(){
$.ajax({
    url:'config.json',
    type:'GET',
    success:function(data){
        var tmpData = JSON.parse(data);
        $("#name").val(tmpData.name);
        $("#last_name").val(tmpData.last_name);
    }
});
});
</script>
</body>
</html>

config.json配置文件

{
    "name": "John",
    "last_name": "Doe"
}

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

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