有没有一种方法可以从与网页相同的服务器上的文本文件加载数据

Is there a way to load data from a text file on the same server as the web page?

本文关键字:服务器 文本 数据 加载 文件 网页 一种 方法 有没有      更新时间:2023-09-26

最近我开始开发一个简单的自上而下的程序,在这个程序中,你可以在地图上移动玩家角色,并放大和缩小地图。

一切都很顺利,我画了一个背景,现在我想开始画一些瓷砖。

目前我有一个看起来像这样的东西:

var tileset1 = new Image();
tileset1.src = "Images/Tileset1.gif";
var tx = [];
var ty = [];
var txo = [];
var tyo = []; //Background tile x and y on the map and the x and y offset in the image for drawing
var tilesize = 32; //constant for each tiles width and height in pixels.
function map1data() {
    "use strict";
    tx[0] = 0;
    ty[0] = 0;
    txo[0] = 0;
    tyo[0] = 0;
    tx[1] = 32;
    ty[1] = 0;
    txo[1] = 32;
    tyo[1] = 0;
}
map1data();
ctx.drawImage(tileset1, txo[i], tyo[i], tilesize, tilesize, tx[i], ty[i], tilesize, tilesize);

这很好,但我的主要问题是使用数组绘制瓦片,并且必须通过将其硬编码到脚本中来给出每个瓦片的属性。

如果我的地图上有100个瓦片,我将不得不手动编写400行代码,这并不理想。

所以我想知道的是,有没有一种方法可以在网页所在的实际服务器上获取一个纯文本文件(如中所示,在与索引页相同的根文件系统中?),并为其内容设置一个变量,就像我对图像所做的那样?而不是必须使用DOM从特定的服务器url请求它?

您不想使用ajax有什么原因吗?您可以按如下方式使用PHP(假设以下文件名为myscript.PHP):

//place any opening javascript code here if necessary.
<?php
     // open a file using the fopen function
     // read each line of the file using the fgets function
     // convert each line into your appropriate javascript code such as an array etc.
     // echo the javascript code
//place any closing javascript code here if necessary.

然后,您可以像包含任何其他javascript文件一样包含它:

<script src="myscript.php"></script>

此外,由于它是在PHP脚本中,您可以引用文件,无论它们是在web根目录中还是在web根之外。

您可以使用XMLHttpRequest API。这样做的目的是告诉浏览器从服务器请求指定的文件,而不加载新页面并将其呈现给用户。然后,您可以将返回的数据分配给代码中的一个变量,并在那里使用它。

如果你不介意使用jQuery,你可以使用.get()方法,它有更简单的语法:

$.get( "tiles.txt", function( data ) {
  // assign 'data' to an existing variable or pass into a function
});

您可能希望将数据存储为JSON或其他类似格式,而不是纯文本(这样更容易操作)。