質問

For some reason, when I use fwrite to overwrite the contents of my file, it erases the data, but fails to write the new contents to it until fwrite is invoked a second time. Is there any way I can get around this?

My script uses HttpRequest to send a FormData object to an external script as if I had invoked a form submit, then the script saves the form data to a file on the server, and then uses another HttpRequest to get the responseText of the file on the server and apply it to the value of another element:

PHP.php
data = $_POST["name"];
fopen(filename, w);
fwrite(file, data);
fclose(file);

CORE.html
<script>
function functionName() {

obj = new XMLHttpRequest;
form = new FormData;
form.append("name", object.getElementById(elementId).value);
obj.open(POST, PHP.php, false);
obj.send(form);

obj2 = new XMLHttpRequest;
obj2.onreadystatechange = function() { if (obj2.readyState == 4 && obj2.status == 200) document.getElementById(elementId2).value = obj2.responseText };
obj2.open(POST, OUTPUT.txt, false);
obj2.send();
}
</script>

<textarea id=elementId onkeypress=functionName()>
</textarea>
<br>
<textarea id=elementId2>
</textarea>

OUTPUT.text
epty text document
役に立ちましたか?

解決 2

I figured it out myself.

For some reason, using the onkeypress event, the event was being triggered and the function called before any characters were inserted into the TextArea, resulting in the file being written with an empty string.

The reason for the successful writes on subsequent attempts was that on subsequent key presses, characters were then present within the TextArea, and were successfuly written to the file.

I simply used another method to call the function after characters were present.

他のヒント

Use fflush()

http://php.net/manual/en/function.fflush.php

This function forces a write of all buffered output to the resource pointed to by the file handle.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top