且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

包含.txt内容WITHOUT服务器端lang?

更新时间:2023-11-27 21:51:58



http: //api.jquery.com/load/



关于如何使用客户端语言(如Javascript)动态加载内容。



这里还有一个问题:

在div /模式框中加载变量的内容



显示如何加载数据放入一个变量中做一些处理和解析。

I have some data stored in a text file, with values separated like this: Name1 | Number1 | Name2 | Number2 |

I call some separate values with php like this:

<?php
$fp = fopen('db.txt','r');
if (!$fp) {echo 'ERROR'; exit;}
$loop = 0;
while (!feof($fp)) {
$loop++;
$line = fgets($fp, 1024); //use 2048 if very long lines
$field[$loop] = explode ('|', $line);
?>

<p>Some text.. <?php echo ''.$field[$loop][2].''; ?></p>
<p>Some more text. Text and value <?php echo ''.$field[$loop][4].''; ?></p>

<?php
$fp++; }
fclose($fp); 
?>

Now I need build the exact same site, loaded from the same database (the .txt-file) but I can't use any php or server side lang at all. Is there any way to do this without server side so that I can save my files as .html? Is it possible to include a text file (and call separated values) with javascript?


Found something like this, but I don't know how to separate the values and only call/get one value at a time? Right now the whole text file is displayed in the span. Would be nice if you could do something similar to the php code.

<script>
jQuery.get('db.txt', function(data) {
   $('#text').html(data.replace('|','<br />'));
});
</script>

 <span id="text"></text>

Can you help me out here? :S


UPDATE: My answer

This is what I've got, think it works pretty well, or do you have any suggestions how to improve it?

<script type="text/javascript">
jQuery.get('db.txt', function(data) {
    $('#db').html(data);
     var element = $("#db").text().split("|"); 
     $('#1').text(element[1]);
     $('#3').text(element[3]);
   });
  </script>

  <span id="db" style="display:none;"></span>

  <span id="1"></span>
  <span id="3"></span>

If my text file looks like this Name1 | Number1 | Name2 | Number2 | it will display:

Number 1 Number 2

Look at the instructions here:

http://api.jquery.com/load/

On how you can use client side language such as Javascript to load content dynamically.

There is also another question here:

loading contents of variable in div/modal box

Showing how you can load that data into a variable to do some processing and parsing.