即使PHP页面回应了某些内容,Ajax对PHP页面的调用也始终不返回任何内容

时间:2012-08-05 17:37:44

标签: php javascript ajax

我用一些同样简单的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页面的内容 Click here for the live PHP page

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

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

2 个答案:

答案 0 :(得分:2)

如上所述,AJAX请求通常仅在调用者和被调用者位于同一域时才有效。您必须确保包含javascript的html代码驻留在同一个域http://www.convolutedconstruct.com上。

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

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

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

答案 1 :(得分:1)

我不喜欢使用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/