1

我有 2 个文件(call.php 和 post.php)并使用 ajax 从调用到 post 传递值,我想从 post 获取返回值,但这不起作用。当我更改帖子时,将“return”修改为“echo”,它可以工作,但我不知道为什么。有人可以帮我吗?
例子将不胜感激。

调用.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));
?>

更新:</p>

相比之下,当我使用 MVC 时,“return”会触发。

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();
                }
            });
4

2 回答 2

2

这是预期的行为,Ajax 会将所有内容输出到浏览器。

return仅当您将返回值与另一个 php 变量或函数一起使用时才有效。

简而言之,php 和 javascript 不能直接通信,它们只能通过 php 回显或打印的内容进行通信。在使用 Ajax 或 php 和 javascript 时,您应该使用 echo/print 而不是 return。


事实上,据我所知,return在 php 中甚至不经常在全局范围内使用(在脚本本身上)它更有可能在函数中使用,所以这个函数保存一个值(但不一定输出它)所以你可以在 php.ini 中使用该值。

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()方法是模型中的一个方法,它将其值返回给控制器,控制器将echo这个值返回到视图中。

于 2013-08-02T08:10:03.250 回答
0

在$.ajax()中使用dataType选项

dataType: "json"

post.php 中试试这个,

<?php
    $name = $_POST['name'];
    echo json_encode(array('name'=>$name));// echo your json
    return;// then return
?>
于 2013-08-02T07:54:09.663 回答