[英]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函數中將數據輸出到頁面
success: function(data){
$('body').append(data.currency.rates[0].mid);//change the body element with your element
},
視圖
@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
所有數據進行渲染
當用戶觸發select更改時,將進行ajax調用,你將收到一個json數據(array)
,你將在div
填充這個數據,稱為ajax_currency
(你從正常的頁面訪問中回顯你的數據)希望它現在是干凈的。
這樣你就不會重新渲染一個視圖,你只需通過JS更改它的一部分。
好吧也許再一次,因為我們可能會誤解。
我有一個觀點:
@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。 當第一次加載頁面時,當有人從下拉列表中更改時,我需要獲得美元的基本值,因此該用戶選擇的貨幣結果應該更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.