首页 > 解决方案 > 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);
?>

标签: javascriptphpserver

解决方案


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);

推荐阅读