gpt4 book ai didi

javascript - Ajax请求从php文件获取数据?

转载 作者:行者123 更新时间:2023-11-28 07:36:44 25 4
gpt4 key购买 nike

我一直在研究如何发出 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”和“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() 属性,因为它比普通脚本更简单(原理相同)。

关于javascript - Ajax请求从php文件获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28516822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com