我正在尝试将一个Eloquent模型对象作为Ajax响应返回,这是我从搜索过程中获得的,我想将其传递给视图。
JS
$(document).ready( function() {
$(".client_search_option").change(function(){
var selectedClientTypeVal = "";
var selectedSmsDecisionVal = "";
var selectedClientType = $('input[type=radio][name=clientType]:checked');
var selectedSmsDecision = $('input[type=radio][name=sms_decision]:checked');
if (selectedClientType.length > 0) {
selectedClientTypeVal = selectedClientType.val();
}
if (selectedSmsDecision.length > 0) {
selectedSmsDecisionVal = selectedSmsDecision.val();
}
//alert(selectedClientTypeVal);
//alert(selectedSmsDecisionVal);
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'http://localhost/pages/clientSearchAjax',
type: 'POST',
data: {_token: CSRF_TOKEN, selectedClientTypeVal:selectedClientTypeVal,selectedSmsDecisionVal:selectedSmsDecisionVal},
dataType: 'JSON',
success: function (data) {
console.log(data);
},
error:function(){
alert("An error has occured !");
}
});
});
});
控制器
public function clientSearch(){
$client_option = Input::get('selectedClientTypeVal');
$sms_option = Input::get('selectedSmsDecisionVal');
if($client_option == 'all' && $sms_option == 'all'){
$ajax_clients = Client::with('clientType')->paginate(5);
}else{
$ajax_clients = Client::with('clientType')->where('clienttype_id', $client_option)->where('send_sms', $sms_option)->paginate(5);
}
return $ajax_clients->toJson();
}
我确信$ajax_client
对象不为null,我测试它并且我能够从数据库获取数据但是当我想将它传递给视图(或控制台)时,它显示为{{1 }}。如何将其传递给视图(或控制台)并获取模型列的值。任何帮助将不胜感激。
答案 0 :(得分:0)
尝试替换
return $ajax_clients->toJson();
与
return $ajax_clients;
Laravel会自动将Eloquent对象转换为JSON,而且它会将内容类型标题设置为 application / json ,这是您在代码中未执行的操作以及可能导致您描述的问题的内容。