2017-05-10 101 views
1

我需要将数据存储在服务器side.I试图让一个Ajax调用PHP: upload.html:如何使用JavaScript而不使用ActiveXObject将数据写入文本文件?

<html> 
 
<head> 
 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 
 
<style> 
 
#test{ 
 
padding:20px 50px; 
 
background:#ccc; 
 
color:#000; 
 
} 
 
</style> 
 
<script> 
 
$(function(){ 
 
$('#test').click(function(){ 
 
    $.ajax({ 
 
     url: "http://localhost:8012/myFolder/upload.php", 
 
\t \t type : 'POST', 
 
     data: {"foo": "bar"}, 
 
     processData: false, 
 
     contentType: 'application/json' 
 
    }); 
 

 
}); 
 
}); 
 
</script> 
 
</head> 
 
<body> 
 

 
<button id="test">KLICK</button> 
 

 

 
</body> 
 
</html>

upload.php的:

<?php 
 
$myFile = "testFile.txt"; 
 
$fh = fopen($myFile, 'w'); 
 
fwrite($fh,$_POST['data']); 
 
fwrite($fh,$_POST['foo']); 
 
fwrite($fh,$_POST["foo"]); 
 
fwrite($fh,$_POST[foo]); 
 
fclose($fh); 
 
?>

但它数据不会对testFile.txt产生影响。 我会感谢您的帮助。 在此先感谢。

+0

类似的QU:http://stackoverflow.com/questions/21012580/is-it-possible-to-write-data -to-file-using-only-javascript –

回答

0

不,JavaScript没有写入文件的权限,因为这至少可以说是一个巨大的安全风险。

但是,如果您想获取/存储服务器端的信息,您当然可以对PHP/ASP/Python /等进行Ajax调用。脚本,然后可以在服务器中获取/存储数据。如果您的意思是在客户端计算机上存储数据,则这是不可能仅限于JavaScript

如果您只是试图针对特定用户针对不可靠的一段时间存储少量信息,我认为您需要cookie。

更新:

下面是一个简单的代码,您正在寻找。有四个领域的简单形式。点击提交后,它会调用服务器文件,该PHP文件将具有将数据写入文件的代码。

$("#submit").click(function(){ 
 
    var paramsToSend = {}; 
 
    var i = 1; 
 
    $("input[name='myanswer[]']").each(function(){ 
 
    paramsToSend[i] = $(this).val(); 
 
    i++; 
 
    }); 
 
    
 
    $("#dataToSend").html(JSON.stringify(paramsToSend)); 
 
    
 
    $.ajax({ 
 
     type: "POST", 
 
     url: 'URL_HERE/post.php', 
 
     data: {params:JSON.stringify(paramsToSend)}, 
 
     success: function(data) { 
 
      console.log("SUCCESS!!!"); 
 
     } 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="inputsl"> 
 
    <div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div> 
 
    <div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div> 
 
    <div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div> 
 
    <div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div> 
 
</div> 
 
<button id="submit"> 
 
Submit 
 
</button> 
 

 
<div id="dataToSend"></div>

PHP代码可以是:

file_put_contents('filename.txt', $_POST['params']); 
+0

您也可以尝试[localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API),而不是Cookie。 –

+0

它不起作用。 – dani

+0

我在ajax调用的url中放入了“http:// localhost:8012/myFolder/upload.php”,并把“testFile.txt”放在php文件中,但是内容并不对文件感到愤怒。 – dani

相关问题