Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

the book of javascript 2nd edition phần 8 ppsx
Nội dung xem thử
Mô tả chi tiết
322 Chapter 16
The \n puts a line break into the file, which creates a two-line file in this case.
If the write is successful, $success will contain the value TRUE; if not, it will contain the value FALSE.
Once you’ve written to a file, close it with fclose():
fclose($myFile);
Combining these lines gives you the PHP script below:
<?php
$myFile = fopen("myFile.txt", "w");
$success = fwrite($myFile, "line one\nline two");
fclose($myFile);
if ($success == TRUE) {
print "Write succeeded";
} else {
print "Write failed";
}
?>
One of the more pernicious problems you’ll encounter when dealing
with server-side programming is that of ensuring that your webserver has
permission to alter the files you want to alter. Sometimes a PHP program can
fail to write to a file because the webserver running it does not have access to
that particular file. If this happens, PHP will give an error like this:
Warning: fopen(yourFile.txt) [function fopen]: failed to open stream:
Permission denied.
File permissions work differently on different operating systems. If you
get this kind of error, refer to your operating system’s manuals to determine
how to inspect and modify file permissions.
Reading Files in PHP
It’s a bit trickier to read a file using PHP than it is to write to a file. The
complication arises because the contents of a file are read line by line, and
PHP needs to know when it has reached the end of a file so that it can stop
reading. Luckily, the PHP function feof() will tell PHP when it has reached
the end of a file. This function takes a variable that points to an open file
(such as $myFile) and returns TRUE when the end of the file has been reached.
Figure 16-13 shows an example of PHP reading a file.
<?php
X $myFile = fopen("myFile.txt","r");
$contents = "";
Y while (feof($myFile) == FALSE) {
Z $contents = $contents . fgets($myFile);
}
Server-Side Ajax 323
[ fclose($myFile);
print "The file's contents are: " . $contents;
?>
Figure 16-13: Reading a file with PHP
In Figure 16-13, X opens the file for reading and puts a pointer to the
opened file into the variable $myFile. The most complicated line is Y, which
calls the feof() function on $myFile to see whether PHP has reached the end
of the file. If not, feof() returns FALSE, and the line inside the while loop is
executed. This line uses the function fgets() to read a line from $myFile.
It takes that line and attaches it to the end of the $contents variable, so each
time through the loop the next line of $myFile is appended to the end of
$contents. Eventually, the last line of $myFile will be read and the feof()
function will respond with TRUE. When that happens, the loop ends, and the
program returns the contents of the file.
NOTE Notice how similar PHP and JavaScript are. They have identically structured while
loops, they both use two equal signs to see whether two things are the same, and they both
use the values TRUE and FALSE (although in JavaScript these values are lowercase).
When Communication Breaks Down
When a web browser contacts a webserver for information, many things can
go wrong. Here are some examples:
z The page being requested may not actually be on the server.
z The user may not have permission to access the page.
z If a server-side program is being called, something might go wrong with
that program.
z The server might take too long to get back to the web browser, and the
browser might stop waiting.
When a request object sends a request and then says that the request
has been fulfilled (its readyState is 4), all we really know is that the request has
been answered in some way. Everything could have gone well, with the server
sending the information requested, or something may have gone wrong.
To determine how the client-server communication went, we can check
the status property of the request object for a status code, as listed in
Table 16-1.
The most frequent numbers you’ll see are 200, if everything went well;
404, if the URL provided to the request object does not exist on the server;
and 500, if the request went to a server-side program, but something went
wrong with the program. Somewhat less frequently you may see a 401 or 403
if the page or program you are trying to access is password-protected, 408 if
the server took too long to respond, or 503 if the server exists but the serverside program you are sending the request to does not.
324 Chapter 16
Typically, you should make sure that the request was satisfied and everything went well (status code 200). To do so, add an if-then statement to
JavaScript functions that make Ajax calls, as shown in Figure 16-14.
request.open("GET", some_url);
request.onreadystatechange = function() {
X if (request.readyState == 4) {
Y if (request.status == 200) {
doSomething();
} else if (request.status == 404) {
Z document.getElementById("errorDiv").innerHTML =
'Sorry, the page you are accessing could not be found.';
} else if (request.status == 500)
document.getElementById("errorDiv").innerHTML =
'Sorry, there was a problem with the server.';
} else {
document.getElementById("errorDiv").innerHTML =
'Sorry, communication breakdown. Please try again.';
}
}
}
Figure 16-14: Adding a status check to an Ajax call
In this code sample, once the request object has reached readyState == 4
(X), we check its status. If the status is 200 (Y), then we do whatever it is
that we want to do when the request has been answered. If not, then we want
to tell the user that something went wrong—in this example, by putting a
message into a div with the id of errorDiv (Z).
Table 16-1: Request Object Status Codes
Status Code Meaning
200 OK
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
407 Proxy Authentication Required
408 Request Time-out
411 Length Required
413 Requested Data Entity Too Large
414 Requested URL Too Long
415 Unsupported Media Type
500 Internal Server Error
503 Service Unavailable
504 Gateway Time-out
Server-Side Ajax 325
Automatically Updating a Web Page When a Server-Side File
Changes
Figures 16-15 and 16-16 demonstrate how to use HEAD calls, server-side file
reading, and the cache-tricking technique to read a file from a webserver,
display its contents, and update the contents whenever the file on the server
changes. This type of application is useful whenever more than one person
can update a file on a webserver—for example, if two people have access to
the same To Do list.
<html><head><title>Automatically Updating Display of a Changed File</title>
<script type = "text/javascript">
<!-- hide me from older browsers
var timeout;
function callReadFile(file_name) {
X readFileDoFunction(file_name, "GET",
Y function() {
if (request.readyState == 4) {
if (request.status == 200) {
var last_modified = request.getResponseHeader("Last-Modified");
var last_modified_date = new Date(last_modified);
displayResults(request.responseText, file_name,
last_modified_date.getTime());
}
}
}
);
}
function readFileDoFunction(file_name, read_type, the_function) {
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
Z var the_url =
"http://localhost/boj/ch16/readTextFile.php?fileName=" +
file_name +
"&t=" + new Date().getTime();
var the_results;
if (request) {
[ request.open(read_type, the_url);
\ request.onreadystatechange = the_function;
request.send(null);
} else {
alert("Sorry, you must update your browser before seeing" +
" Ajax in action.");
}
}
function displayResults(the_results, file_name, last_modified) {
326 Chapter 16
document.getElementById("contents").innerHTML = the_results;
] timeout = setTimeout("callUpdateIfChanged(" + last_modified + ",'" +
file_name + "')", 5000);
}
function callUpdateIfChanged(current_last_modified, file_name) {
readFileDoFunction(file_name, "HEAD",
function() {
if (request.readyState == 4) {
if (request.status == 200) {
var last_modified =
request.getResponseHeader("Last-Modified");
var last_modified_date = new Date(last_modified).getTime();
if (last_modified_date != current_last_modified) {
callReadFile(file_name);
}
timeout = setTimeout("callUpdateIfChanged(" +
last_modified_date + ",'" + file_name + "')", 5000);
}
}
}
);
}
function stopTimer() {
clearTimeout(timeout);
}
// show me -->
</script>
</head>
<body>
<form>
<input type = "button" value = "Read the File"
onClick = "callReadFile('numbers.txt');">
<input type = "button" value = "Stop Checking" onClick = "stopTimer();">
</form>
<div id = "contents">
</div>
</body>
</html>
Figure 16-15: Client-side checking for updated server-side file
Figure 16-15 lists the client-side portion of the application. Clicking the
Read the File button in the form at the bottom calls the callReadFile() function and sends it the name of a file to read. The callReadFile() function does
only one thing—it calls a function named readFileDoFunction(), which does
the actual work of getting the file. We’ll take a look at readFileDoFunction()
first and then turn back to callReadFile().