1

我正在尝试一个基本的 AJAX 调用,我将地址“www.google.com”发送到,urlpost.php但当前代码似乎无法检测到响应(没有任何反应)。我试图寻找错误,但我不知道我哪里出错了。

谢谢大家!

免责声明:这是 Robin Nixon 的Learning PHP, MySQL & Javascript示例的变体

索引.html

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Ajax Example</title>
    </head>
    <body>

    <h1 align='center'>Loading a web page into a DIV</h1>
    <div id='info' align='center'>This Sentence will be replaced </div>
    <script>
        request = new ajaxRequest()
        request.open("POST", "urlpost.php", true) //also tried 'test/urlpost.php' (test is the folder of the file)
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
        request.setRequestHeader("Content-length", params.length)
        request.setRequestHeader("Connection", "close")                

        request.send("url=www.google.com")

        request.onreadystatechange = ajaxCallback

        function ajaxCallback()
        {
            alert("Reponse received") //just letting me know I got a reponse
            if(this.readyState==4) //ready
            {
                if (this.status==200) //no idea
                    {
                        if (this.responseText != null)
                            {
                                document.getElementById('info').innerHTML = this.responseText
                            }
                        else alert("AJAX ERROR: NO DATA RECEIVED")
                    }
                    else alert("Ajax error: "+this.statusText);
            }
        }

        function ajaxRequest()
        {
            try //non IE browser
            {
                var request = new XMLHttpRequest();
            }
            catch(e1)
            {
                try // IE6+?
                {
                    request = new ActiveXObject("Msxml2.XMLHTTP")
                }
                catch(e2)
                {
                    try // IE5?
                    {
                        request = new ActiveXObject("Microsoft.XMLHTTP")                   
                    }
                    catch(e3) //No Ajax support
                    {
                        request = false
                    }
                }
            }   
            return request
        }

    </script>

urlpost.php

<?php
if (isset($_POST['url'])){
    echo file_get_contents("http://".$_POST['url']);
}

?>
4

2 回答 2

2

使用 jQuery 重写它,更容易。

$(document).ready(function(){

        $.ajax({
            type: "post",
            url: "urlpost.php",
            data: "url=www.google.com",

            success: function(msg){
                $('#replace').html(msg);

            }
        });
    return false;

});​
于 2012-06-23T21:15:09.210 回答
1

request.setRequestHeader("Content-length", params.length)

params.length未定义。您需要将其替换为您发送的数据的长度

request.send("url=www.google.com")在您的情况下,这是 18 个字符。

于 2012-06-23T21:33:56.000 回答