2013-08-02 41 views
1

我有2个文件(call.php和post.php)和使用ajax传递值从调用发布,我想从帖子返回值,但这是行不通的。当我改变职位,修改“返回”为“回声”,它的工作原理,但我不知道why.an任何人给我一个帮助?
例子将不胜感激。Ajax返回值与返回不起作用

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

将某些东西放到PHP的流中时,使用'echo'。添加在$ .ajax()中使用此选项时使用'return'用于PHP – NoLifeKing

回答

2

这是预期的行为,阿贾克斯将获得输出到浏览器的一切。

return只适用于您将返回的值与另一个php变量或函数一起使用。

简而言之,php和javascript不能直接通信,它们只能通过php回显或打印进行通信。当使用Ajax或PHP与JavaScript时,你应该使用回声/打印,而不是返回。


事实上,据我所知,return在PHP甚至没有在全球范围内经常使用(在脚本本身)它更可能在函数中使用,所以此功能包含一个值(但不一定输出它),所以你可以在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()方法与模型,它的值返回到控制器的方法,控制器echo该数值到视图。

+0

我确切地知道“回报”是如何工作的,你的回答与我的问题不符 – wusuopubupt

+0

宇,你说的后来帮了我很多! – wusuopubupt

1

使用dataType$.ajax()

dataType: "json" 

选项在post.php中试试这个,

<?php 
    $name = $_POST['name']; 
    echo json_encode(array('name'=>$name));// echo your json 
    return;// then return 
?> 
+0

中使用此选项 dataType:“json”,仍然不工作 – wusuopubupt

+0

实际上dataType选项是可选的.. Ajax数字表明它自己... – bipen

+0

@ wusuopubupt是否在'alert'中获得了'data'? –