我正在努力让这段代码发挥作用。我的目的是能够将div的内容保存到html文件中,以便我以后再调用它...
它部分有效,因为如果我在$data=$_POST['id']
中将$data=$_POST['memory']
更改为readInput.php
,它确实会将我输入的任何文本保存到名为“内存”的输入中。到一个html文件,并将使用我给它的任何名称正确保存文件。失败的地方是,如果我尝试获取DIV 'readDiv'
及其内容$data=$_POST['id'];
的数据,它将保存一个空白的html页面,无论我给它的名字是什么......这是代码:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>readInput</title>
<meta name="description" content="HTML5 web page">
<meta name="keywords" content="HTML5">
<meta name="author" content="You">
<meta charset="UTF-8">
<link href="jquery-ui.htm" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-latest.htm"></script>
<script name="saveMemory" type="text/javascript">
$(document).ready(function() {
$('#saveMemory').click(function() {
//e.preventDefault();
var content = $('#readDiv').html(); // orig
//var content = document.getElementById('readDiv').value; // test
$.ajax({
type: 'POST',
url: 'readInput.php',
data: {id: content}
//dataType: "html" // test
});
});
});
</script>
</head>
<body onload="document.readWrite.writeInput.focus();"><!--form name.input name.focus!-->
<div id="formContainer" style="display:block">
<form name="readWrite" action="readInput.php" method="POST">
<input name="memory" placeholder="...enter text here..." type="text">
<input name="readMemory" id="readMemory" class="readMemory" placeholder="...read..." type="text">
<input id="writeInput" name="writeInput" class="writeInput" placeholder="...write..." type="text">
<input class="saveMemory" id="saveMemory" name="saveMemory" value="...saveMemory..." type="submit">
</form></div>
<div name="readDiv" id="readDiv" class="readDiv">
<div id="writeDiv" class="writeDiv" title="writeDiv">test text
<div id="topDropbox" class="topDropbox" title="topDropbox">
<img src="car.jpg">
</div></div></div>
</body></html>
readInput.php
:
<?php
$writeInput = $_POST['writeInput'];
$data = $_POST['id'];
$fileName = ("memories/$writeInput.html");
$fileHandle = fopen($fileName, 'w+') or die("Cannot open file");
fwrite($fileHandle, $data);
fclose($fileHandle);
echo($fileName);
echo($data);
?>
对于专业人士来说,这可能看起来像是一个糟糕的黑客工作,因为我已经尝试了很多代码,而且我确信我只是错过了一些愚蠢的东西,但我感到很茫然...谢谢任何人的任何帮助!
答案 0 :(得分:0)
此更新应该可以解决问题:
$(document).ready(function() {
$('#saveMemory').click(function(e) {
e.preventDefault();
var content = $('#readDiv').html(); // orig
//var content = document.getElementById('readDiv').value; // test
$.ajax({
type: 'POST',
url: 'readInput.php',
data: {id: content, writeInput : $('#writeInput').val()}
//dataType: "html" // test
}).done(
function( data ){
$('#result).html( data);
}
);
});
});
的变化:
e
。它为函数提供了对事件对象的引用。e.preventDefault()
,因此表单不会执行中断ajax调用。writeInput
。.done
)。请求完成后,此函数将执行将responseData
写入writeDiv
直接在body标签中添加以下div。
<div id="result" style="background-color: #f4f4f4;width:100%;height:300px;overflow: auto"></div>