2017-12-18 344 views
0

我想返回一個url作爲Ajax響應。但在此之前,我使用遞歸功能來展平保持鍵的多維數組。問題,同時返回ajax響應

function response(){ 
    ... 
    $response = Ezpay::PayWithToken($obj); 
    $trans_resp = json_decode(json_encode($response),true); 
    $resp_array = $this->flatten($trans_resp); 
    //saving transaction response from gateway to sessioion 
    Session::push('ezpay_gateway_resp',json_encode($resp_array)); 
    print_r(Session::get('ezpay_response')) 
    return '/gateway/success'; 
} 

和遞歸函數是

function flatten($array, $prefix = '') { 
     $result = array(); 
     foreach($array as $key=>$value) { 
      if(is_array($value)) { 
       $result = $result + $this->flatten($value, $key); 
      } 
      else { 
       $result[$key] = $value; 
      } 
     } 
     return $result; 
} 

'/gateway/success'

+1

在從哪兒獲取'$ trans_resp'你的迴應方法是什麼? – linktoahref

+0

$ response = Ezpay :: PayWithToken($ obj); $ trans_resp = json_decode(json_encode($ response),true); – Shalom

+0

在'$ this-> flatten($ trans_resp)',其中''trans_resp'來自函數response()'。對不起如果我在以前的評論中不清楚 – linktoahref

回答

0

現在正在返回$result陣列istead從您的代碼print_r(Session::get('ezpay_response'))

顯示使用頁面上的文本echo

echo '/gateway/success'; 
+0

刪除。我只是改了名字,但它不是問題 – Shalom

+0

你改變了什麼名字? – madalinivascu

+0

你確定你在調用response()而不是flatten()嗎? – madalinivascu

0

,應該回送的網址:

function response(){ 
    $resp_array = $this->flatten($trans_resp); 
    //saving transaction response from gateway to sessioion 
    Session::push('ezpay_gateway_resp',json_encode($resp_array)); 
    echo '/gateway/success'; 
} 

這是一個完整的例子。

控制器:

namespace App\Http\Controllers; 
use Illuminate\Http\Request; 
use App\Http\Requests; 
use App\Http\Controllers\Controller; 

class ExampleController extends Controller 
{ 
    public function message() 
    { 
     $msg = "myurl/index"; 
     return response()->json(array('msg'=> $msg), 200); 
    } 
} 

路線:

Route::get('ajax',function() 
{ 
    return view('message'); 
}); 
Route::post('/msg','[email protected]'); 

的Javascript使用它:

function getMessage(){ 
    $.ajax({ 
     type:'POST', 
     url:'/msg', 
     data:'_token = <?php echo csrf_token() ?>', 
     success:function(data){ 
      $("#msg").html(data.msg); 
     } 
    }); 
}