XMLHttpRequest意外返回通信错误



我是PHP的新手,在编写一段代码时遇到了困难。我正在使用一个例子,来自学习PHP,MySQL和amp;JavaScript。其意图是以<div>gt;。我没有显示google.com的主页,而是获得了"通信错误:状态:500内部服务器错误";。有人能告诉我我做错了什么吗。

目录结构为:

amvetsfl292.org
public_html
PHP

PHP目录中包含的文件有:

Filename           Size   Description            Permission
async_request.js    478   JScript Script File    0644
test_php.html      1427   Firefox HTML Document  0644
url_post.php        408   PHP File               0644

我执行来自Firefox Developer的测试脚本,地址为

amvetsfl292.org/PHP/test_php.html

我不知道为什么谷歌主页没有显示。

下面是源代码文件。

test_php.html:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Asynchronous Communication Example</title>
</head>
<body style="text-align:center;">
<h1>Loading a web page into a DIV</h1>
<div id="info">This sentence will be replaced</div>
<script src="async_request.js" ></script>
<script>
var params = "url=https://www.google.com";
var request = new async_request ( );
request.open ( "POST", "url_post.php", true );
request.setRequestHeader ( 
"Content-type",
"application/x-www-form-urlencoded" );
request.onreadystatechange =
function ( )
{
if ( this.readyState == 4 )
{
if ( this.status == 200 )
{
if ( this.responseText !== null )
{
document.getElementById ( "info" ).innerHTML =
this.responseText;
}
else 
{
alert ( "Communications error - No data received" );
}
}
else 
{
alert ( "Communications error: " + 
"status: " + this.status +
" " + this.statusText );
}
}
};
request.send ( params );
</script>
</body>
</html>

async_request.js

/* jsl:option explicit */
function async_request ( )
{
try 
{
var request = new XMLHttpRequest ( );
}
catch ( e1 )
{
try 
{
request = new ActiveXObject ( "Msxml2.XMLHTTP" );
}
catch ( e2 )
{
try 
{
request = new ActiveXObject ( "Microsoft.XMLHTTP" );
}
catch ( e3 )
{
return ( false );
}
}
}
return ( request );
}

url_post.php

<?php // url_post.php
if ( isset ( $_POST [ "url" ] ) )
{
echo file_get_contents ( "https://" . 
sanitize_string ( $_POST [ "url" ] ) )
}

function sanitize_string ( $var ) 
{
if ( get_magic_quotes_GPC ( ) )
{
$var = stripslashes ( $var );
}
$var = strip_tags ( $var );
$var = htmlentities ( $var );
return ( $var );
}
?>

url_post.php第6行缺少";">

添加缺少的分号后,代码以不同的方式运行,但仍有错误。在错误日志中,我发现该软件正试图访问该网站htpps://https://www.google.com这当然是不存在的。我从更改了params变量

var params = "url=https://www.google.com";

var params = "url=www.google.com";

不仅错误消失了,谷歌主页也出现了。教训-警惕书中的例子。

感谢每一个人的想法。

最新更新