2017-05-10 13 views
0

私はTymeleafでSpring Bootを使用しており、かなり新しいです。私はTwitter APIを使ってアプリを作っています。私はth:eachを使って表示されたつぶやきのリストを持っています。ユーザーがツイートのリトウェットボタンをクリックすると、その特定のツイートのIDをリトウェットメソッドのパラメーターとしてコントローラーに送信し、リトウェットメソッドで処理できるようにする必要があります。ユーザーは、フロントエンドからのIDを認識すべきではありません。Springでのフォーム入力ではなく、コントローラへの変数の送信方法

今のところ、私の唯一の解決策は、「」タグ内のURLとIDが含まれており、それはコントローラで@PathVariableを使用してパス変数として採用されており、つぶやきのリストを持っているインデックスページを返すことです。これはうまく動作しますが、私はこの方法が嫌いです。ユーザーがページを離れてはいけないので、あとでモーダルを使うほうがいいかもしれません。基本的には、IDをHTMLに表示せずにコントローラに送信する方法を知りたいです。

index.htmlを

<div class="result" th:each="result : ${results}"> 
      <h3><a th:href="${result.fromUser}" th:text="${result.user.name}"></a></h3> 

      <p th:text="'@' + ${result.fromUser}"></p> 
      <span th:text="${result.text}"></span> 
      <div id="retweet"> 
        <a th:href="'user/' + ${result.id}">Retwt</a> 

      </div> 
     </div> 

Maincontroller.java

@RequestMapping(value = "") 
public String getUserProfile(Model model) { 
    TwitterProfile userInfo = twitterService.getUserProfile(); 
    List<Tweet> homeTimeline = twitterService.getUserTimeline(); 
    model.addAttribute("profileImg", userInfo.getProfileImageUrl()); 
    model.addAttribute("results", homeTimeline); 
    return "pages/index"; 
} 

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET) 
public String retweet(@PathVariable long id) { 
    twitterService.retweet(id); 
    return "/"; 
} 
+0

あなたはリロードせずにバックエンドにメッセージを送信する場合ページを表示するには、JavaScriptを使用してデータを送信する必要があります。これは、JavaScripts XMLHttp、またはそれを少し楽にするJQueryのようなフレームワークを使用して行うことができます。 –

答えて

1

これは、jQueryのAJAX HTTP GETを使用して怒鳴るとアクセスとしてあなたのコントローラメソッドを変更達成することができます。 AJAX要求を受け入れるようにコントローラを変更

@ResponseBody  
    @RequestMapping(value = "/user", method = RequestMethod.GET) 
    public String retweet(@RequestBody Long id) { 
     twitterService.retweet(id); 
     return "/"; 
    } 

変更あなたのHTML、

<div class="result" th:each="result : ${results}"> 
      <h3><a th:href="${result.fromUser}" th:text="${result.user.name}"></a></h3> 

      <p th:text="'@' + ${result.fromUser}"></p> 
      <span th:text="${result.text}"></span> 
      <div id="retweet"> 
        <a href="JavaScript:Void(0);" th:onclick="'doRetweet(\'' + ${result.id} + '\');'" >Retwt</a> 

      </div> 
     </div> 

jQueryの部分、

     function doRetweet(userId){ 
         var data = JSON.stringify(userId) 
         if (data) { 
          $.ajax({ 
           url : '/user', 
           headers : { 
            'Content-Type' : 'application/json' 
           }, 
           method : 'GET', 
           dataType : 'json', 
           data : data, 
           success : function(data) { 
            if (data.status == 200) { 
             // Handle success response 
            } 
           }, 

           error : function(xhr, status, error) { 
            // Handle errors here 
           } 
          }); 
         } 
        } 
+0

ありがとう、私は完全にjqueryを忘れてしまった。 – Zuse

関連する問題