从javascript中的文本文件中获取价值

时间:2015-04-03 23:33:48

标签: javascript html variables get

我有一个javascript变量,我在我的html网站上显示,我还有一个.txt文件,它从.php脚本中获取付款值。这些值在.txt文件中显示为12345,每个数量都会增加1,所以首先.txt文件获得1然后是2然后是3等等。现在我的问题是,如何从.txt获取最后一个值文件并将我的变量值转换为我得到的值,通过.txt文件的最后一个值我的意思是如果文件中的当前值是12345然后最后一个值是5,那么我想将我的Javascript中的变量更改为价值5。

我的javascript / html脚本包含变量并显示在里面。

<div class="newValue">
        Current value: $<span id="newValueVariable"></span>
</div>

 <script type="text/javascript"> 

        var newValueVariable= 1;
        document.getElementById("newValueVariable").innerHTML = newValueVariable;

</script>

1 个答案:

答案 0 :(得分:2)

使用AJAX:

var xhr = new XMLHttpRequest;
xhr.open("filename.txt", "GET", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var contents = xhr.responseString;
        // Replace next line with what you actually use to parse the file
        var lastChar = contents.substr(-1, 1);
        document.getElementById("newValueVariable").innerHTML = lastChar;
    }
}
xhr.send();