【发布时间】:2015-12-28 05:00:20
【问题描述】:
我是 AJAX 新手。我正在发送一个请求以在另一个需要发生几件事的页面上启动 PHP 代码。我在该页面上有一个算法,检查所有事情是否按正确的顺序正确完成。我需要的是将该布尔值返回给 AJAX 文件,以便它知道请求不仅已收到,而且以预期的方式完成,以便我可以添加一个 success: 函数为用户提供 OK/NEY 体验。
【问题讨论】:
我是 AJAX 新手。我正在发送一个请求以在另一个需要发生几件事的页面上启动 PHP 代码。我在该页面上有一个算法,检查所有事情是否按正确的顺序正确完成。我需要的是将该布尔值返回给 AJAX 文件,以便它知道请求不仅已收到,而且以预期的方式完成,以便我可以添加一个 success: 函数为用户提供 OK/NEY 体验。
【问题讨论】:
您的文件夹:
AnyFolderName
|--- index.php
|--- script.php
索引.php:
<!DOCTYPE html>
<html>
<head>
<title>AJAX Request Sample</title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
function submitform(){
//get value of input whos id is username
var username = $('input#username').val();
//data to post to script.php
var post = {username: username};
$.ajax({
url: "script.php", //<-- PHP Script where you want to post your data
type: "POST",
data: post,
success: function(data){
//callback when request is finished.
//in our script.php, we just echoed the posted username, so it alerts whatever username you have input.
alert(data);
}
});
}
</script>
</head>
<body>
<form id="myForm">
<input id="username" name="username">
</form>
<button onclick="submitform();"></button>
</body>
</html>
script.php:
<?php
//print out the posted data you have passed from the AJAX request
echo $_POST['username'];
?>
【讨论】:
您可以在 AJAX 的成功函数中返回(成功为 true,失败为 false)变量。在此基础上,您可以继续下一步。
虚拟示例:
$.ajax({
url: '',
type:'POST',
data: {'id':id},
dataType:'json',
beforeSend:function(){
},
error : function(xhr, textStatus, errorThrown) {
alert('An error occurred!');
},
success:function(response){
if(response){
console.log('yes');
}
else{
console.log('no');
}
}
complete: function() {
}
});
【讨论】:
哦,这是我的错。浏览了几十页,但终于在另一个线程上找到了答案(所以我的有点重复):
How to return data from PHP to a jQuery ajax call
必须使用 echo();而不是 return();在 PHP 文件中! 当然,还有相应的数据类型,在本例中为“文本”。
【讨论】:
这是我的解决方案....
$.ajax(
{
类型:'POST',
网址:'../some/file/file.php',
async: true, //这很重要!!!
成功:函数(响应)
{
如果(响应)
{
//使用本地环境存储保存数据
localStorage.setItem('数据',响应);
}
}
});
//请求数据
some_variable = localStorage.getItem('data').trim(); //修剪很重要!!!
玩得开心!!!!
【讨论】: