我有两个文件(call.php和post.php),并且从调用到post使用ajax值,我希望从post中获得返回值,但这是行不通的。当我更改帖子,将“返回”修改为“回显”时,它可以工作,但我不知道why.can有人帮我吗?
Examples would be most appreciated. call.php
<script type="text/JavaScript">
$(document).ready(function(){
$('#submitbt').click(function(){
//var name = $('#name').val();
//var dataString = "name="+name;
var dataPass = {
'name': $("#name").val()
};
$.ajax({
type: "POST",
url: "post.php",
//data: dataString,
data: dataPass,//json
success: function (data) {
alert(data);
var re = $.parseJSON(data || "null");
console.log(re);
}
});
});
});
</script>post.php:
<?php
$name = $_POST['name'];
return json_encode(array('name'=>$name));
?>最新情况:
相比之下,当我使用MVC时,“返回”会触发。
public function delete() {
$this->disableHeaderAndFooter();
$id = $_POST['id'];
$token = $_POST['token'];
if(!isset($id) || !isset($token)){
return json_encode(array('status'=>'error','error_msg'=>'Invalid params.'));
}
if(!$this->checkCSRFToken($token)){
return json_encode(array('status'=>'error','error_msg'=>'Session timeout,please refresh the page.'));
}
$theme = new Theme($id);
$theme->delete();
return json_encode(array('status'=>'success'));
}
$.post('/home/test/update',data,function(data){
var retObj = $.parseJSON(data);
//wangdongxu added 2013-08-02
console.log(retObj);
//if(retObj.status == 'success'){
if(retObj['status'] == 'success'){
window.location.href = "/home/ThemePage";
}
else{
$('#error_msg').text(retObj['error_msg']);
$('#error_msg').show();
}
});发布于 2013-08-02 08:10:03
这是预期的行为,Ajax将把所有的东西输出到浏览器。
只有在将返回的值与另一个php变量或函数一起使用时,return才能工作。
简而言之,php和javascript不能直接通信,它们只能通过php回显或打印的内容进行通信。当在javascript中使用Ajax或php时,您应该使用echo/print,而不是返回。
事实上,据我所知,php中的return甚至不经常用于全局范围(在脚本本身上)--它更可能用于函数中,因此该函数包含一个值(但不一定是输出值),因此您可以在php中使用该值。
function hello(){
return "hello";
}
$a = hello();
echo $a; // <--- this will finally output "hello", without this, the browser won't see "hello", that hello could only be used from another php function or asigned to a variable or similar.它使用MVC框架,因为它有几个层,可能delete()方法是来自模型的一个方法,它将它的值返回给控制器,控制器将这个值返回到视图中。
发布于 2013-08-02 07:54:09
在dataType中使用$.ajax()选项
dataType: "json"在post.php中试试这个,
<?php
$name = $_POST['name'];
echo json_encode(array('name'=>$name));// echo your json
return;// then return
?>https://stackoverflow.com/questions/18011592
复制相似问题