Ajax对PHP页面的调用总是不返回任何内容,即使PHP页面有回声


Ajax call to a PHP page always returns nothing even though the PHP page echoes something

我正在用一些同样简单的AJAX调用一个非常简单的PHP页面,但即使PHP很好,调用也总是不返回任何结果。也就是说,您可以转到PHP页面的URL,看到它与"Hello World"相呼应,但当使用JS调用它时,它什么也不返回。

下面是带有Javascript的HTML页面:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......<br />
Enter your email: <input id="email" type="text" />
<input type="button" onclick="setXMLHttpRequest()" value="Go!" />
<script type='text/javascript'/>
        var http;
        function setXMLHttpRequest()
        {
            if(window.XMLHttpRequest)
                http = new XMLHttpRequest();
            else if(window.ActiveXObject)
                http = new ActiveXObject("Microsoft.XMLHTTP");
                url = "http://www.convolutedconstruct.com /Ajax/checkemail.php?email=" + 
                                   document.getElementById('email').value;
                http.onreadystatechange = display;
                http.open("GET", url, true);
                http.send(null);
        }
        function display()
        {
            if (http.readyState == 4)
            {   
                infostr = http.responseText;
                alert("From the PHP: " + infostr);
            }
        }
</script></body></html>

以下是PHP页面的内容点击此处查看实时PHP页面

<?php
$email = $_GET['email'];
echo "Hello World!";
?>

为什么即使PHP页面正确地回显了文本,这也不会向JS返回任何内容?

正如上面所建议的,AJAX请求通常只有在调用方和被调用方都在同一域上时才能工作。您必须确保包含javascript的html代码位于同一域http://www.convolutedconstruct.com.

如果不是这样的话,您可以使用CORS允许ajax通过在php输出中发送此标头来接收来自php页面的输入

<?php
header("Access-Control-Allow-Origin: *");
//rest of your code
?>

请参阅:http://enable-cors.org/

我不喜欢使用XMLHTTP请求。相反,我使用jQuery的方法$.ajax({});方法。它总是对我有用!

$.ajax({
    type: "POST", // or 'GET'
    url: "your-url.php", // url that you are passing the data to
    data: {
        dataName: 'data to pass' // string, variable, object, array, etc
    },
    success: function(output) { // output is what the url is 'echoing' back to the jQuery
        // do something when the ajax method is complete.
    }
});

不要忘记导入jQuery源代码-http://code.jquery.com/jquery-1.7.2.min.js

这些是ajax中使用的最常见的组件。

如果你愿意的话,我很乐意再帮你一些。

如果您想了解更多信息,请查看上面的文档:http://api.jquery.com/jQuery.ajax/