1

2 つのファイル (call.php と post.php) があり、call から post への ajax パス値を使用しています。post から戻り値を取得したいのですが、これは機能しません。投稿を変更し、「return」を「echo」に変更すると機能しますが、理由がわかりません。誰か助けてもらえますか?
例をいただければ幸いです。

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));
?>

更新:</p>

対照的に、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();
                }
            });
4

2 に答える 2

2

これは予想される動作であり、Ajax はすべてをブラウザーに出力します。

return返された値を別の php 変数または関数で使用している場合にのみ機能します。

つまり、php と javascript は直接通信できず、php がエコーまたは出力したものを介してのみ通信します。javascript で Ajax または php を使用する場合は、return の代わりに echo/print を使用する必要があります。


実際、私が知る限り、returnphp はグローバル スコープでも (スクリプト自体では) 頻繁に使用されることはなく、関数で使用される可能性が高いため、この関数は値を保持します (必ずしも出力するとは限りません)。その値を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この値をビューに返します。

于 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 に答える