[英]Javascript PHP write file to server
I am using javascript to send data to php file on server, the php file will write the received data into a text file on server.我正在使用javascript将数据发送到服务器上的php文件,php文件会将接收到的数据写入服务器上的文本文件中。
Javascript Javascript
var data = "data123";
var request = new XMLHttpRequest();
request.open('POST', 'http://......../save.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
PHP file on server服务器上的 PHP 文件
<?php
$test =$_GET['data'];
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= $test;
// Write the contents back to the file
file_put_contents($file, $current);
?>
I tried the code above, but the text file didn't change.我尝试了上面的代码,但文本文件没有改变。
You have two problems.你有两个问题。
$_GET
which contains data from the query string and not the request body.$_GET
读取数据,其中包含来自查询字符串而不是请求正文的数据。 Use $_POST
$_POST
application/x-www-form-urlencoded
but are actually just sending text/plain
.application/x-www-form-urlencoded
但实际上只是发送text/plain
。 You need to encode the data. eg例如
var key = "data";
var encodedData = encodeURIComponent(key) + "=" + encodeURIComponent(data);
request.send(encodedData);
Your are using POST method on your ajax request, so in your php use $_POST
instead $_GET
您在 ajax 请求中使用 POST 方法,因此在您的 php 中使用
$_POST
代替$_GET
$test =$_POST['data'];
And in your javascript use =
into your string like :并在您的 javascript 中使用
=
到您的字符串中,例如:
var data = "data=123";
It doesn't seem like you "post" the data or set the parameter name "data" from your javascript.您似乎没有“发布”数据或从您的 javascript 设置参数名称“数据”。 If you do
如果你这样做
var_dump($_POST['data'])
I'm quite certain you will not get 'data123';我很确定你不会得到“data123”;
If you post data it will reside in " $_POST " and if you get data it will have to be fetched from " $_GET ".如果您发布数据,它将驻留在“ $_POST ”中,如果您获取数据,则必须从“ $_GET ”中获取。 Or both are usually added to " $_REQUEST ".
或者两者通常都添加到“ $_REQUEST ”中。
Instead, you will have to set the names like相反,您必须将名称设置为
var params = 'data=data123';
and then send your params然后发送你的参数
http.send(params);
The fetch it from the correct array depending on if you send using get or post.根据您是使用 get 还是 post 发送,从正确的数组中获取它。
You have to send your data with a key您必须使用密钥发送数据
var data = encodeURIComponent("data123");
//...
request.send('data=' + data);
The PHP part should be as following: PHP 部分应如下所示:
<?php
$data = $_POST['data'];
$file = __DIR__ . '/people.txt'; //its not needed to add the dir
//use the FILE_APPEND flag to append your data its faster than loading the whole contents
file_put_contents($file, $data, FILE_APPEND);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.