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()属性,因为它比普通脚本更简单(原理相同)。
相关文章:
- Ajax-如何获取数据
- 从键值结构中获取数据,并将其与AngularJS中ng重复的值进行比较
- 从数据库中获取数据并插入JavaScript变量
- 从单击的行上的列中获取数据
- Solr查询以按日期月份获取数据&年
- React路由器服务器端渲染和ajax获取数据
- 使用JavaScript在IE9中获取数据列表选项
- 从json子数组获取数据
- 使用angularjs中的rest调用通过id获取数据
- 正在从ruby应用程序中的数据库中获取数据
- 如何从servlet获取数据到ajax成功
- 从选择下拉菜单中获取数据
- 异步获取数据使用JavaScript同步获取数据
- 从服务器获取数据并在选择控件中使用ng选项无法显示选项
- 如何在Angular.js中循环动态添加Fields并获取数据并将其发送到服务器
- JavaScript-获取数据属性的值返回未定义的值
- 如何从文本区域获取数据并使用javascript进行解密
- 在put方法之前从作用域获取数据
- 事件循环的MEAN.JS setInterval进程(从另一个服务器获取数据)
- 使用ReactJS和Flux架构从服务器获取数据的正确方法是什么