首页 > 解决方案 > 为什么我收到错误: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);
}
?>

标签: javascriptphphttp-status-code-405asynchronous-javascript

解决方案


推荐阅读