2016-03-20 12 views
1

Bahar mvc 4 öğreniyorum ve şablon motoru olarak thymeleaf kullanıyorum ... Basit bir soru var .. Görüntülenecek ürünlerin bir listesini var ve kullanıcı örneğin benzeri bir düğmeye tıklayabilir.ajax ile arama yöntemleri ve bir değişken yay mvc döndürme 4

Öğrendiklerimden html öğeleri, sunucu eşlemelerini istek eşlemesini kullanarak uygun yöntemi çağıran href (ajax olsun veya olmasın) yoluyla çağırır, ancak bu yöntemler görünüm adını temsil eden bir dize döndürür. ancak bir görünüm vermek istemiyorum, örneğin, kullanıcı isabet ettiğinde, yalnızca DB'yi değiştiren ve bir boole döndüren ve buna dayanan bir yöntemi çağırmak istiyorum. DB gibi bir düğmenin rengini değiştiriyorum değişiklik başarılı olduysa veya başarısız olursa bir hata mesajı .. bunu nasıl yapabilirim? İşte DÜZENLEME

bir benzeri düğme yüzden kullanıcı için DB güncelleme ve benzeri yerleştirme olmadığını dönebilir bir ürün üzerinde tıklandığında (sadece ajax istek gönderin ulaşmak için çalışıyorum ne basit bir örnek

<!DOCTYPE html> 
<html xmlns:th="http://www.thymeleaf.org"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<meta name="viewport" 
    content="width=device-width, initialscale=1, maximum-scale=1.0, user-scalable=no" /> 
<title>Home</title> 

<link rel="stylesheet" type="text/css" media="all" 
    th:href="@{https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css}" 
    th:integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" 
    th:crossorigin="anonymous" /> 
<!-- Optional theme --> 
<link rel="stylesheet" type="text/css" media="all" 
    th:href="@{https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css}" 
    th:integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" 
    th:crossorigin="anonymous" /> 
</head> 
<body> 
    <div class="container"> 
     <div class="row"> 
      <div class="col-xs-12"> 
       <table class="table"> 
        <tr> 
         <th>ID</th> 
         <th>Name</th> 
         <th>Description</th> 
        </tr> 
        <tr th:each="prod : ${products}"> 
         <td th:text="${prod.id}">Id</td> 
         <td th:text="${prod.name}">Product Name</td> 
         <td th:text="${prod.desc}">Product Description</td> 
         <td> 
          <div th:id="${prod.id}"> 
           <button id="like-btn">Like</button> 
          </div> 
         </td> 
         <td></td> 
        </tr> 
       </table> 
      </div> 
     </div> 
    </div> 


    <script 
     th:src="@{https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js}"></script> 
    <script th:inline="javascript"> 
    $("#like-btn").click(function() { 
     var divId = $(this).parent().attr('id'); 

     $.ajax({ 
      type: "GET", 
      url: ("http://localhost:9090/like?prodId=" + divId), 
      success: function(){alert("Submit succeeded");}, 
      fail: function(){alert("Submit failed");} 
     }); 
    }); 
    </script> 
</body> 
</html> 

Bahar Kontrolörü: veritabanına)

Thymeleaf Template başarılı olup

@Controller 
public class HomeController 
{ 
    @RequestMapping("/") 
    public String getHomePage() 
    { 
     return "home"; 
    } 

    @RequestMapping("/products") 
    public String getProducts(Model model) 
    { 
     ArrayList<Product> products = new ArrayList<>(); 

     Product p1 = new Product(); 
     p1.setId(1); 
     p1.setName("Product 1"); 
     p1.setDesc("Product 1 Description"); 
     products.add(p1); 

     Product p2 = new Product(); 
     p2.setId(2); 
     p2.setName("Product 2"); 
     p2.setDesc("Product 2 Description"); 
     products.add(p2); 

     model.addAttribute("products", products); 

     return "products"; 
    } 

    @RequestMapping(value="/like", method=RequestMethod.GET) 
    public boolean likePage(@RequestParam("prodId") int productId) 
    { 
     System.out.println("Prod ID: " + productId); 
     //DB insert and modification and return result code, just a sample here 
     //to be processed by jquery 
     //if(insertionSucceeded) 
      return true; 
     //else 
     // return false; 
    } 
} 

ama tabiki bunun gibi bir şablon olmadığını söyleyen bir hata veriyor. Bu kodu deneyebilirsiniz

+0

Bunu ajax'ta yapmak ister misiniz? – Lucky

+0

evet, bunu ajax içinde yapmak istiyorum –

+0

@Lucky Soruyu –

cevap

0

,

$("#like-btn").click(function(){ 
    var prodLikeId = $(this).parent().attr('id'); 
    $.ajax(function(){ 
     type: "GET", 
     dataType: "json", 
     url: "http://localhost:9090/like?prodId="+prodLikeId, 
     success: function(response){ 
      alert("Submit succeeded"+response); 
      if(response===true){ 
       window.alert("Update the HTML"); 
       //update the like button color here 
       $('#like-btn').css('color','blue'); 
      } 
     }, 
     error: function(e){ 
      alert("Submit failed"+e); 
     } 
    }); 
}); 

Ve Kontrolör içinde

, sen ajax incelemek için araçları gibi @ResponseBody ek açıklama ve ajax yöntemleri için produces = "application/json",

@RequestMapping(value="/like", method=RequestMethod.GET,produces = "application/json") 
public @ResponseBody Boolean likePage(@RequestParam("prodId") int productId) 
{ 
    System.out.println("Prod ID: " + productId); 
    //DB insert and modification and return result code, just a sample here 
    //to be processed by jquery 
    //int res = productService.insertProductLike(productId); 
    //if(res>0) 
     return true; 
    //else 
    // return false; 
} 

Kullanım Kundakçı eklemem gerekiyor çağrı yanıtlama verisini doğrular. Ya da sizin yöntem tipiniz olarak bir Map<String,String> kullanabilir ve map.put("success","true"); gibi haritayı doldurarak yanıtı geri alabilirsiniz. Bu response.success ile başarı bloğunda bu erişebilir ve buna HTML verilerini göstermek veya güncelleme olabilir bu anahtar-değer çifti json yanıt dayalı

{"success":"true"} 

, böyle bir json dize yanıt verecektir.

+1

thx çok istiyorum basit bir örnekle düzenledim .. bu harika çalışıyor çünkü dinlenmeyi kullanıyorum beri bahar güvenliği ile ilgili sorun yaşıyorum .. ama çözüm doğru, benim sorun şimdi dinlenme ve normal kontrolörler için bahar güvenlik yapılandırma ile .. thx –