我想将$data
变量从findCity()
函数传递给json返回到索引函数中的视图。
我该怎么办呢?
class HomeController extends Controller
{
public function index(Request $request)
{
$countries = Location::select('country_name')
->groupBy('country_name', 'country_name')
->get();
$cities = Location::select('city_name','city_name')
->where('region_name', $request->region_name)
->groupBy('city_name', 'city_name')
->get();
$areas = Area::get()->toTree();
return view('home', compact('areas','countries', 'cities'));
}
public function findCity(Request $request)
{
$data = Location::select('city_name','city_name')
->where('region_name', $request->region_name)
->groupBy('city_name', 'city_name')
->get();
return response()->json($data);
}
}
Ajax代码:
$(document).on('change','.regionName',function(){
//console.log("hmm its change");
var cat_id=$(this).val();
//console.log(cat_id);
var div=$(this).parent();
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findCityName')!!}',
data:{'region_name':cat_id},
success:function(data){
//console.log('success');
//console.log(data);
//console.log(data.length);
op+='<option value="0" selected disabled>Choose City</option>';
for(var i=0;i<data.length;i++){
op+='<option value="{{ route('user.location.store', $cities) }}">'+data[i].city_name+'</option>';
}
div.find('.cityName').html(" ");
div.find('.cityName').append(op);
},
error:function(){
}
});
});
});
答案 0 :(得分:0)
您可以将findCity()
设为静态方法,并从index()
方法中调用它:
public function index(Request $request)
{
// The rest of your code here...
// Calling the static method
$city = self::findCity($request);
return view('home', compact('areas', 'countries', 'cities', 'city'));
}
public static function findCity(Request $request)
{
$data = Location::select('city_name', 'city_name')
->where('region_name', $request->region_name)
->groupBy('city_name', 'city_name')->get();
return $data;
}
答案 1 :(得分:0)
您需要使用函数调用,传递和返回。像这个。我认为它可以帮助你。
class HomeController extends Controller
{
public function index(Request $request)
{
$countries = Location::select('country_name')
->groupBy('country_name', 'country_name')
->get();
$cities = $this->findCity($request)
$areas = Area::get()->toTree();
return view('home', compact('areas','countries', 'cities'));
}
public function findCity($request)
{
$data = Location::select('city_name','city_name')
->where('region_name', $request->region_name)
->groupBy('city_name', 'city_name')
->get();
return response()->json($data);
}
}