javascript - 将文本保存到 html 服务器上的 txt 文件?
问题描述
我正在建立一个小型网站,我遇到了一个问题,我想在按下按钮时将硬编码的数字保存到 .txt 文件中。
我已经在其他网站上尝试了一些在线示例,但是我唯一一次可以做同样的事情是当我使用 php 并且它不是在按下按钮时
...
<br>
<br><table id="tblCustomers" style="width: 100%;">
<tr>
<td style="width: 50%;">
<button onclick="location.href='{% url 'script'
%}'">Execute Script</button> <hr>
//On this button it should save a 23 to a txt
file wich is in the same folder and has the
name contacts.txt
</td>
<td style="width: 50%;"><input type="button"
id="btnread" value="Count Rows" /></td>
</tr>
</table>
...
这是我尝试过的其他东西,它不起作用。
解决方案
您不能使用 Javascript 直接写入文件 - 能够这样做的安全隐患不值得考虑。您可以做的是(或其中之一)将使用 Javascript 发送请求以将数据保存到后端脚本,该脚本确实有权访问并能够写入服务器上的文件。
例如 - 使用fetch
api 向 PHP 脚本发送请求(它与这里的演示文档相同,但可能是完全不同的脚本) - PHP 代码处理获取请求并执行两个任务之一 - 要么将数据写入在发送 fetch 回调的响应以进行处理/播放之前,文件或从中读取。
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
$file='test-contacts.txt'; # write to this file
$json=json_decode( file_get_contents( 'php://input' ) ); # get the request body
$action=!empty( $json ) && property_exists( $json, 'action') ? $json->action : false;
$value=!empty( $json ) && property_exists( $json, 'value') ? $json->value : false;
switch( $action ){
case 'execute':
$data = array( 'bytes'=>file_put_contents( $file, $value . PHP_EOL, FILE_APPEND ), 'value'=>$value, 'time'=>time() );
break;
case 'count':
$data=array( 'bytes'=>filesize( $file ), 'time'=>time(), 'count'=>sizeof( file( $file ) ) );
break;
default:
http_response_code( 400 );
exit( json_encode('error') );
}
http_response_code( 200 );
header('Content-Type: application/json');
exit( json_encode( $data ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
document.addEventListener('DOMContentLoaded',()=>{
/* find and assign event handler to the buttons */
Array.from( document.querySelectorAll('td > input[ type="button" ]') ).forEach( bttn=>{
bttn.addEventListener('click',function(e){
/* prepare the Fetch request */
let url=location.href;
let options={
method:'post',
headers:{ 'Content-Type':'application/json' },
body:JSON.stringify({
action:this.name,
value:23 /* seems very peculiar hard-coding a value to be written to file!!! */
})
};
/* The callback to process returned JSON data */
const callback=function( json ){
let out=document.querySelector( 'output' );
out.innerHTML='';
Object.keys( json ).map( k=>{
let div=document.createElement('div')
div.innerText=[k,json[k]].join('=');
out.appendChild( div );
});
};
/* If there are errors... */
const errorcallback=function(err){
alert( err )
};
/* Send the request and manipulate the response */
fetch( url, options )
.then( r=>{ return r.json() })
.then( callback )
.catch( errorcallback );
});
})
});
</script>
</head>
<body>
<table id='tblCustomers'>
<tr>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
</tr>
</table>
<output></output>
</body>
</html>
如果尝试记录不同的值(如评论所建议的那样),建议对数据结构进行细微更改,以便可以正确记录每个 ID。然而,我对数据库所做的评论仍然有效,但也许以下内容可能有用。
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
$file='test-contacts.txt'; # write to this file
$json=json_decode( file_get_contents( 'php://input' ) ); # get the request body
$action=!empty( $json ) && property_exists( $json, 'action') ? $json->action : false;
$value=!empty( $json ) && property_exists( $json, 'value') ? intval( $json->value ) : false;
$data=file_exists( $file ) ? json_decode( file_get_contents( $file ) ) : new stdclass;
switch( $action ){
case 'execute':
$data->$value=isset( $value ) && isset( $data->$value ) ? $data->$value + 1 : 1;
file_put_contents( $file, json_encode( $data ) );
break;
case 'count':
$value=isset( $data->$value ) ? $data->$value : 0;
$data=new stdclass;
$data->count=$value;
break;
default:
http_response_code( 400 );
exit( json_encode('error') );
}
http_response_code( 200 );
header('Content-Type: application/json');
exit( json_encode( $data ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
document.addEventListener('DOMContentLoaded',()=>{
/* find and assign event handler to the buttons */
Array.from( document.querySelectorAll('td > input[ type="button" ]') ).forEach( bttn=>{
bttn.addEventListener('click',function(e){
/* prepare the Fetch request */
let url=location.href;
let options={
method:'post',
headers:{ 'Content-Type':'application/json' },
body:JSON.stringify({
action:this.name,
value:this.parentNode.parentNode.dataset.id
})
};
/* The callback to process returned JSON data */
const callback=function( json ){
let out=document.querySelector( 'output' );
if( out ) out.innerHTML='';
Object.keys( json ).map( k=>{
let div=document.createElement('div')
div.innerText=[ k, json[ k ] ].join('=');
out.appendChild( div );
});
};
/* If there are errors... */
const errorcallback=function(err){
alert( err )
};
/* Send the request and manipulate the response */
fetch( url, options )
.then( response => { return response.json() } )
.then( callback )
.catch( errorcallback );
});
})
});
</script>
</head>
<body>
<table id='tblCustomers'>
<tr data-id=23>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
</tr>
<tr data-id=24>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
</tr>
<tr data-id=25>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
</tr>
<tr data-id=26>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
</tr>
</table>
<output></output>
</body>
</html>
删除条目或删除整个内容可以这样完成:
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
$file='test-contacts.txt'; # write to this file
$json=json_decode( file_get_contents( 'php://input' ) ); # get the request body
$action=!empty( $json ) && property_exists( $json, 'action') ? $json->action : false;
$value=!empty( $json ) && property_exists( $json, 'value') ? intval( $json->value ) : false;
$data=file_exists( $file ) ? json_decode( file_get_contents( $file ) ) : new stdclass;
switch( $action ){
case 'execute':
$data->$value=isset( $value ) && isset( $data->$value ) ? $data->$value + 1 : 1;
file_put_contents( $file, json_encode( $data ) );
break;
case 'count':
$value=isset( $data->$value ) ? $data->$value : 0;
$data=new stdclass;
$data->count=$value;
break;
case 'clear':
$data=unlink( $file );
break;
case 'delete':
if( property_exists( $data, $value ) && !empty( $data->$value ) ){
unset( $data->$value );
file_put_contents( $file, json_encode( $data ) );
}
break;
default:
http_response_code( 400 );
exit( json_encode('error') );
}
http_response_code( 200 );
header('Content-Type: application/json');
exit( json_encode( $data ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
document.addEventListener('DOMContentLoaded',()=>{
/* find and assign event handler to the buttons */
Array.from( document.querySelectorAll('td > input[ type="button" ]') ).forEach( bttn=>{
bttn.addEventListener('click',function(e){
/* prepare the Fetch request */
let url=location.href;
let options={
method:'post',
headers:{ 'Content-Type':'application/json' },
body:JSON.stringify({
action:this.name,
value:this.parentNode.parentNode.dataset.id
})
};
/* The callback to process returned JSON data */
const callback=function( json ){
let out=document.querySelector( 'output' );
if( out ) out.innerHTML='';
Object.keys( json ).map( k=>{
let div=document.createElement('div')
div.innerText=[ k, json[ k ] ].join('=');
out.appendChild( div );
});
};
/* If there are errors... */
const errorcallback=function(err){
alert( err )
};
/* Send the request and manipulate the response */
fetch( url, options )
.then( response => { return response.json() } )
.then( callback )
.catch( errorcallback );
});
})
});
</script>
</head>
<body>
<table id='tblCustomers'>
<tr data-id=23>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
<td><input type='button' name='delete' value='Delete record' /></td>
<td><input type='button' name='clear' value='Clear file' /></td>
</tr>
<tr data-id=24>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
<td><input type='button' name='delete' value='Delete record' /></td>
<td><input type='button' name='clear' value='Clear file' /></td>
</tr>
<tr data-id=25>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
<td><input type='button' name='delete' value='Delete record' /></td>
<td><input type='button' name='clear' value='Clear file' /></td>
</tr>
<tr data-id=26>
<td><input type='button' name='execute' value='Execute Script' /></td>
<td><input type='button' name='count' value='Count Rows' /></td>
<td><input type='button' name='delete' value='Delete record' /></td>
<td><input type='button' name='clear' value='Clear file' /></td>
</tr>
</table>
<output></output>
</body>
</html>
推荐阅读
- python - 收到以下错误..TypeError:在 python 中使用 2D numpy 数组时不理解数据类型
- java - Jenkins 作业失败,出现错误 java.lang.NoClassDefFoundError
- c# - Cassandra C# 结果不断增加
- php - Drupal 网站抓取
- json - 触发器从 PostgreSQL 中的 JSON 对象创建记录
- node.js - Mongoose find 不返回结果 mongo 确实
- java - 在 Spring 上下文中模拟 bean
- angular - 如何管理具有相同路线的多个项目?
- pandas - Pandas - 将日期列从 dd/mm/yy hh:mm:ss 转换为 yyyy-mm-dd hh:mm:ss
- ios - pod和模块有什么区别