javascript - javascript/php to save string in file on server
问题描述
I am fairly new to javascript and php. I am trying to save a variable in javascript in a simply text file on the server. I understand that javascript operates on the browser so I can't use javascript directly. I am trying to pass the string to a php file and save it there but it is not working. Any advice would be appreciated. Here is the javascript:
var data = "test"
var url = "save-to-log.php";
var XML = "data.txt";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST",url,true);
xmlhttp.send("D="+data+'&F='+XML);
and here is the php file which is on the server:
<?php
$NAME = $_POST['F'];
$HANDLE = fopen($NAME, 'w') or die ('CANT OPEN FILE');
fwrite($HANDLE,$_POST["D"]);
fclose($HANDLE);
?>
解决方案
As you send data as POST
param you need to set header application/x-www-form-urlencoded
xmlhttp.open("POST",url,true);
// this line
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send("D="+data+'&F='+XML);
推荐阅读
- python - 使用 h5py 时 PyInstaller 构建时间长
- amazon-web-services - 有没有办法在创建任务方法 Boto3 上自动启动 DMS?
- inno-setup - 如何根据定义的语言使用许可文件
- java - 如何在 Java 中使用 Graphics 添加背景图像
- python - ModuleNotFoundError:没有名为“psycopg2”的模块错误:python3、django、settings.py?
- reactjs - 在 React 应用程序中导入 firebase 中的 ESLint 问题
- rust - Rust 中的并行分段初筛中的生命周期错误
- boundary - 边值分析——有序列表
- node.js - NPM 安装与 nodejs 版本匹配的最新可用版本
- java - Java,代号一:在用户之间导出和 - 最重要的是 - 导入文件