Ajax请求从php文件获取数据


Ajax request to get data from php file?

我一直在研究如何发出Ajax请求,并提出了以下内容:

function ajax_post(){
    // Create our XMLHttpRequest object
    var xmlhttp = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "http://localhost:888...-files/test.php";
    // Set content type header information for sending url encoded variables in the request
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    xmlhttp.onreadystatechange = function() {
   if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
   var return_data = xmlhttp.responseText;
document.getElementById("demo").innerHTML = return_data;
   }
    }
    xmlhttp.open("POST", url, true);
    xmlhttp.send(); // Actually execute the request
    document.getElementById("demo").innerHTML = "processing...";
}

我将此脚本保存为以下文件:http://localhost:888...ascript/test.js<--我已经测试了保存在这个位置的其他脚本,它们运行得非常好。我的php文件包含以下数据(名称为"test.php"):

<?php
echo(rand(10,100));
?>

在我向php文件发出请求后,该文件应该根据php代码显示一个随机数,我的html看起来像这样:

<div style="display:none;">
<body onload="ajax_post()">     <------ Here you can see that I have called the function which executes the AJAX Request after the page has loaded.
<script type="text/javascript" src="http://localhost:888...ascript/test.js"></script>
</body>
</div>
<div id="demo"></div>

我不断刷新页面,但什么都没有显示。这与我的php代码有关吗?也许我的Ajax请求结构错误?在Ajax请求方面,我也尝试过"GET"answers"POST",但仍然没有任何结果。我是Ajax的新手,可能的语法我没有意义。。。提前感谢您的支持。

问候!!

我在php文件中添加了一些html,除了php文件(php显示为注释)之外,所有内容都加载了。然后,我想到了将我创建的php文件与本地服务器上的其他php文件进行比较的想法。我发现了一点不同。其他php文件不会关闭php,即<?php echo 'Hello World';,而不将?>放在末尾,现在它可以工作了。我的php文件如下:

<?php
echo 'Hello World';

我还简化了我的脚本,使我的结构看起来如下:

<div id="demo"><div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready( function() {
$('#demo').load('http://localhost:8888/...php-files/test.php');
});
</script>

我使用了JQuery.load()属性,因为它比普通脚本更简单(原理相同)。