[英]Javascript : Get data through ajax call
It may be possible this question has been posted so many times.But i didn't get answer from those one.I have passed url in Ajax call and i want whatever i'm getting from database through the query,get in success method of ajax request.But somehow i didn't get this. 可能这个问题已经发布了很多次了。但是我没有从那些人那里得到答案。我已经在Ajax调用中传递了url,并且我希望通过查询从数据库中获取任何信息,获得成功的方法ajax request。但是以某种方式我没有得到这个。
Ajax call method: Ajax调用方法:
function validateAmount() {
var amount = document.getElementById("amount").value;
// alert(amount);
// var y = x.value;
$.ajax({
url : "{{url('getAmount')}}",
type : "GET",
async : false,
dataType : "json",
success : function (result) {
alert();
}
});
}
and database query: 和数据库查询:
And this is what i want to return 这就是我要返回的
public function getAmount(){
$user_id = session('user_id');
$res = DB::table('table_name')->where(['user_id'=>$user_id])->first();
return $res;
}
And one more thing,when i simply echo string in getAmount method ,ajax call get succeed but when i try to access the data through query,i'm getting fail. 还有一件事,当我只是在getAmount方法中回显字符串时,ajax调用会成功,但是当我尝试通过查询访问数据时,我会失败。
Please help me to get this. 请帮我得到这个。 Any help will be appreciated.Thanks in advance.
任何帮助将不胜感激。
First : Remove the async: false
as Rory mentioned in the comments. 首先 :删除
async: false
就像评论中提到的Rory一样。
Second: For the ajax you have to use the echo json_encode($my_data_array);
第二:对于ajax,您必须使用
echo json_encode($my_data_array);
Third: Dont use alert
rather use console.log(result)
to view your data. 第三:不要使用
alert
而要使用console.log(result)
来查看数据。
Use Collection::toJson() method to transform you collection to json string: 使用Collection :: toJson()方法将您的集合转换为json字符串:
$res = DB::table('table_name')->where('user_id', $user_id)->first();
return $res->toJson();
Collection::toArray() works too Collection :: toArray()也可以
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.