jQuery初心者です。
非同期のチャットアプリを作っています。
php側からjsonをresponseとして返しているのですが、それをjs側でpartner_id
とlogin_id
で絞り込みたいと思っています。
php側から返したdataの絞り込みがうまくいかないため、改善案のアイデアをいただけたらと思います。
ちなみに、partner_id
とlogin_id
はview側から渡ってくることは確認済みです。
js
$(function() { get_data(); }); function get_data() { $.ajax({ url: "result/ajax/", dataType: "json", success: data => { $("#comment-data") .find(".comment-visible") .remove(); var userID = $("#user_id").val; var partnerID = $("#partner_id").val; for (var i = 0; i < data.comments.length; i++) { var login = $.grep(data.comments[i], function(element){ return (element['login_id'] = userID); }); var partner = $.grep(login.comments[i]['partner_id'], function(element, index){ return (element = partnerID); }); var html = ` <div class="media comment-visible"> <div class="media-body comment-body"> <div class="row"> <span class="comment-body-user" id="name">${partner.name}</span> <span class="comment-body-time" id="created_at">${partner.created_at}</span> </div> <span class="comment-body-content" id="comment">${partner.comment}</span> </div> </div> `; $("#comment-data").append(html); } }, error: () => { alert("ajax Error"); } }); // setTimeout("get_data()", 5000); }
php(Ajaxに関わる箇所のみ抜粋)
public function getData(){ // print_r($request->all()); // $partnerID = $request->input('partner_id'); $comments = Comment::orderBy('created_at', 'desc')->get(); $json = ["comments" => $comments]; return response()->json($json); }
json
{comments: Array(10)} comments: Array(10) 0: {id: 75, login_id: 4, name: "user4", comment: "ghjk", created_at: "2020-04-06 16:27:13", …} 1: {id: 74, login_id: 4, name: "user4", comment: "www", created_at: "2020-04-06 15:29:26", …} 2: {id: 73, login_id: 4, name: "user4", comment: "ddd", created_at: "2020-04-06 15:29:18", …} 3: {id: 72, login_id: 4, name: "user4", comment: "sdfdsds", created_at: "2020-04-06 15:28:56", …} 4: {id: 71, login_id: 4, name: "user4", comment: "asdfg", created_at: "2020-04-06 15:27:06", …} 5: {id: 70, login_id: 4, name: "user4", comment: "sdfghjkl", created_at: "2020-04-06 15:26:30", …} 6: {id: 69, login_id: 4, name: "user4", comment: "sss", created_at: "2020-04-06 15:19:36", …} 7: {id: 68, login_id: 1, name: "user1", comment: "1->4", created_at: "2020-03-31 17:01:26", …} 8: {id: 67, login_id: 1, name: "user1", comment: "1->2", created_at: "2020-03-31 17:01:11", …} 9: {id: 66, login_id: 1, name: "user1", comment: "1→3", created_at: "2020-03-31 16:26:25", …}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。