javascript - 为什么我收到错误:405:JavaScript 和 PHP 中的异步通信中不允许的方法
问题描述
我开始学习 JS 异步通信及其工作原理,并尝试构建一个简单的示例(遵循 Robin Nixon 的“Learning PHP, MySQL & JavaScript”一书)。
我有一个 HTML 文件,其中包含一些 JS (urlpost.html) 和另一个 PHP 文件 (urlpost.php),用于与 HTML 文件进行异步交互。我要做的是首先,HTML 文件<H1>
在<div id="info
. 在异步通信的readyState属性为4(已完成)和状态为200之后,我想<div id="info">
用服务器返回的文本更改里面的句子。
我得到的错误是错误:405 Method Not Allowed
我不确定自己做错了什么,是因为我在代码上做错了什么,还是因为我作为参数传递的 URL 不允许这种通信。我已经花了一些时间试图弄清楚我做错了什么,但在这一点上,我不确定还能做什么。
urlpost.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Asynchronous Communications</title>
</head>
<body>
<h1>Loading a web page into a div</h1>
<div id='info'>
This sentence will be replaced
</div>
<script>
params = "url=news.yahoo.com/"
request = new asyncRequest() //object request is created
request.open("POST", "urlpost.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("communication error: no data recieved")
}
else alert("communication error: " + this.status + ": " + this.statusText)
}
}
request.send(params)
function asyncRequest()
{
try
{
var request = new XMLHttpRequest() //async request for all major browsers
}
catch(e1)
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP") //async request for IE.6+
}
catch(e2)
{
try
{
request = new ActiveXObject("Microsoft.XMLHTTP") //async request for IE5
}
catch(e3)
{
request = false
}
}
}
return request
}
</script>
</body>
</html>
urlpost.php:
<?php
if (isset($_POST['url']))
{
echo file_get_contents('http://' . SanitizeString($_POST['url']));
}
function SanitizeString($var)
{
$var = strip_tags($var);
$var = htmlentities($var);
return stripslashes($var);
}
?>
解决方案
推荐阅读
- apache-spark - Spark 写入 Hive 错误的 table_name 作为分区规范并抛出“分区规范包含非分区列”错误
- ios - 如何添加左右滑动动画显示视图
- python - 无法从我的节点在 firebase 中打印值
- python - Scrapy 每个起始 url 输出一个 CSV 文件
- javascript - sheet.cssRules 在内页上抛出错误,但在主页上工作正常
- scala - rdd中spark scal中的ReduceByKey不起作用
- python - 如何从 Python 脚本访问 fontforge
- c++ - 终端进程以退出代码终止:1 有什么办法可以解决吗?
- node.js - 如何在nodejs应用程序中集成logstash?
- javascript - 将字符串转换为函数名