Ajax显示视图


Laravel 5.3 Ajax show view

我有一个Ajax问题。我有一个控制器,它从外部API得到响应。在这个控制器传递变量到API请求。结果传递给视图。在这个视图中,我有货币的下拉列表。我想当用户选择另一种货币的新请求将被发送到API并生成新的视图。

下面是文件和代码。

web.php

Route::get('/home', 'HomeController@nbp');
Route::post('/home','HomeController@nbp');

HomeController.php

    public function nbp(Request $request)
        {
                $data = $request->all();

            if($request->ajax() && $request->isMethod('post')){
                $data = response()->json($data);
                $data = $data->getContent();
                $data = json_decode($data, true);
                $currency = $data['currency'];
                Debugbar::info($currency);
            }else{
                $currency = 'EUR';
            }
             $tabeA = 'a';
 // Create a client with a base URI
                $client = new GuzzleHttpClient(['base_uri' => 'http://api.nbp.pl/api/'],['headers'=>['content-type'=> 'application/json']]);

                // Send a request
                $response = $client->request('GET', 'exchangerates/rates/'.$tableA.'/'.$currency);
                 $response->getStatusCode();
                // 200
                //$contentType = $response->getReasonPhrase();
                // 'application/json; charset=utf8'
                $currency =  json_decode($response->getBody());
                $data = $currency->rates;
                $data2 = $data[0]->mid;
       if($request->ajax() && $request->isMethod('post')){
             return view('home',compact('currency'))->render();
            }else{
    return view('home',compact('currency'));
            }
                }

script.js

$('#currencyNameA').change(function() {
    $.ajax({
    type:'post',
     dataType: 'json',
     headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
     url: '/home',
      data:  { currency : $('#currencyNameA').val()},
   success: function(data){

   },
   complete: function(data){

   }
  });
});

请求API必须是http://api.nbp.pl/api/$table/$currency

的例子:http://api.nbp.pl/api/a/USD

执行以下操作:

如果你做一个ajax调用从你的控制器返回json:

$currency =  json_decode($response->getBody());
                $data = $currency->rates;
                $data2 = $data[0]->mid;
       if($request->ajax() && $request->isMethod('post')){
             return response()->json(["currency"=>$currency]);
            }else{
    return view('home',compact('currency'));
            }
成功函数中的

将数据输出到页面

 success: function(data){
    $('body').append(data.currency.rates[0].mid);//change the body element with your element
   },

好吧,也许再来一次,因为我们可能误解了。

I have a view:

@extends('layouts.app') @section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Currency</div>
                <div class="panel-body">
                {!! Form::open(array('url' => '/currency','method' =>'post')) !!}
                {!! csrf_field() !!}
                <select name="currency" id="currencyNameA">
                 @foreach($currency_table_A->rates as $rows)
                 <option value="{{ $rows->code }}">{{ $rows->currency }}</option>
                @endforeach
                </select>
                {!! Form::close() !!}
                    <br />
                <h2><div class="currency">
                currency {{$currency->currency}} {{ $currency->rates[0]->mid}} last update was {{ $currency->rates[0]->effectiveDate }}
                </div>
                </h2>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

和控制器:

 public function getCurrency(Request $request)
     {       
          $client = new GuzzleHttpClient(['base_uri' => 'http://api.nbp.pl/api/'],['headers'=>['content-type'=>
 'application/json']]);
             //Table for dropdown list Begin
             $table_response = $client->request('GET','exchangerates/tables/a');
             $currency_table_A =  json_decode($table_response->getBody());
             $currency_table_A = $currency_table_A[0];
             //Table for dropdown list End
         if($request->ajax() && $request->isMethod('post')){
             $cur = $request->input('currency'); //get currency from post
         }else{
             $cur = 'EUR';
         }  
     // Send a request to External API
     $response = $client->request('GET', 'exchangerates/rates/a/'.$cur);
     //Antwser from External API
     $currency =  json_decode($response->getBody());

   if($request->ajax() && $request->isMethod('post')){
        //In Debug bar i get reply form API but my View is not change
        Debugbar::info($currency);
        return response()->json(view('curentCurrency', compact('currency','currency_table_A'))->render());
    }else{
        return view('curentCurrency', compact('currency','currency_table_A'));
    }
    }

Script.js

$('#currencyNameA').change(function() {
    $.ajax({
    type:'post',
     dataType: 'json',
     headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
     url: '/currency',
      data:  { currency : $('#currencyNameA').val()},
   success: function(data){  
   }
  });
});

我需要传递一个新的答案,一个视图当被选择新的货币在下拉列表。当页面第一次加载时,我需要获得美元的基本价值,当有人从下拉列表更改货币结果应该为用户选择更改。

VIEW

@extends('layouts.app') @section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Currency</div>
                    <div class="panel-body">
                    {!! Form::open(array('url' => '/currency','method' =>'post')) !!}
                        {!! csrf_field() !!}
                        <select name="currency" id="currencyNameA">
                            @foreach($currency_table_A->rates as $rows)
                                <option value="{{ $rows->code }}">{{ $rows->currency }}</option>
                            @endforeach
                        </select>
                    {!! Form::close() !!}
                    <br />
                    <h2>
                        <div class="currency" id="ajax_currency">currency {{$currency->currency}} {{ $currency->rates[0]->mid}} last update was {{ $currency->rates[0]->effectiveDate }}</div>
                    </h2>
                </div>
                </div>
            </div>
        </div>
    </div>
@endsection
控制器

public function nbp(Request $request){
    if($request->ajax() && $request->isMethod('post')){
        $cur = $request->input('currency'); //get currency from post
        //Debugbar::info($cur);
    }else{
        $cur = 'EUR';
    }
    $tabeA = 'a';
    // Create a client with a base URI
    $client = new GuzzleHttpClient(['base_uri' => 'http://api.nbp.pl/api/'],['headers'=>['content-type'=> 'application/json']]);
    // Send a request
    $response = $client->request('GET', 'exchangerates/rates/'.$tableA.'/'.$cur);
    $response->getStatusCode();
    // 200
    //$contentType = $response->getReasonPhrase();
    // 'application/json; charset=utf8'
    $currency =  json_decode($response->getBody());
    $data = $currency->rates;
    $data2 = $data[0]->mid;
    if($request->ajax() && $request->isMethod('post')){
        return response()->json(['currency' => $data, 'mid' => $data2, 'updated' => $currency->rates[0]->effectiveDate]);
    }else{
        return view('home', compact('currency'));
    }
}

JS

$('#currencyNameA').change(function() {
  $.ajax({
    type:'post',
    dataType: 'json',
    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
    url: '/home',
    data:  { currency : $('#currencyNameA').val()},
    success: function(data){
        $('#ajax_currency').html('currency '+data.currency+' '+data.mid+' last update was '+data.updated);
    },
    complete: function(data){
      //ajax complete
    }
  });
});

当用户加载页面(不是Ajax)时,视图将呈现与compact的所有数据

当用户触发选择更改ajax调用将作出,你将收到一个json数据(array)和这个数据,你将填充在div称为ajax_currency(你从正常的页面访问回声你的数据)希望它现在是干净的。

这样你就不用渲染视图了,你只需要通过JS改变其中的一部分。