我是Java脚本的新手。
我正在实施一些网页。
现在,我有TextBox字段(供用户输入服务器ip,用户名和密码),上传文件按钮和Submit按钮。我想调用Javascipt脚本函数,该函数从文本框中获取值并将其保存到.txt文件中在服务器上,然后单击“提交”按钮。
使用Java脚本,我可以读取值,但是当我尝试将值写入文件时,它不起作用。当我在网上搜索时,发现了ActiveXObject解决方案,该解决方案仅在IE中有效。但是我正在寻找在所有浏览器中都可以使用的解决方案。
我的环境仅支持javascript和PHP。
请帮我..
您可以使用onchange
绑定到表单的事件,并在发生任何更改时将数据保存到文本文件中。这是通过AJAX请求以静默方式将表单提交给您的服务器来完成的。
Javascript和PHP解决方案:
<form id="stackoverflow" method="POST" action="" onchange="save()">
<input name="subject" type="text" value="Hello World" style="width:222px"><br/>
<textarea name="message" style="width:220px;height:100px">This is an example of sending an AJAX request to PHP and writing it to file.</textarea><br/>
<button type="button" onclick='save()'>Submit</button>
</form><script>
function save() {
var form = document.querySelector('#stackoverflow');
var data = new FormData(form);
var req = new XMLHttpRequest();
req.open("POST", "form-write.php", true);
req.send(data);
console.log("..saved");
}
</script>
每当有人在您的一种表单上进行更改时,此方法就会将数据发送到服务器的PHP文件。一个简单的按键将触发此事件。PHP文件可以做任何您想做的事情,在这种情况下,我们只是将表单字段的内容写到一个简单的文本文件中。
PHP代码:
$subject = $_POST['subject'];
$message = $_POST['message'];
$output = "Subject: {$subject}\n";
$output.= "Message: {$message}";
file_put_contents("form.txt",$output);
输出示例:
主题:Hello World
消息:这是向PHP发送AJAX请求并将其写入文件的示例。
jQuery和PHP解决方案:
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<form id="stackoverflow" method="POST" action="">
<input name="subject" type="text" value="Hello World" style="width:222px"><br/>
<textarea name="message" style="width:220px;height:100px">This is an example of sending an AJAX request to PHP and writing it to file.</textarea><br/>
<button type="button" onclick='save()'>Submit</button>
</form><script>
$("#stackoverflow").change(function(){
save();
});
function save() {
$.post("form-write.php", $('#stackoverflow').serialize() );
console.log("..saved");
}
</script>
在这里,我们将以JSON格式存储表单的内容,因为这是我们最容易使用的形式。JSON文件将包含表单中的所有字段,稍后我们可以使用PHP使用读取json_decode()
PHP代码:
file_put_contents("form.txt",json_encode($_POST));
JSON保存的示例如下所示:
{"subject":"Hello World","message":"This is an example of what JSON looks like."}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句