2013-08-02 43 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'? –