2016-09-04 16 views
2

JavaScript(自分のコントローラのModelに属性として追加された変数)にどのようにアクセスでき、どのようにプロパティを操作できますか?JavaScriptからSpring Model変数にアクセスする

マイモデル:

public class Category { 
    private Long id; 
    private String name; 
    private List<Recipe> recipes = new ArrayList<>(); 
} 

マイコントローラ:私のWebページで

@RequestMapping(path = "/", method = RequestMethod.GET) 
public String showAllCategories(Model model) { 
    List <Category> categories = categoryService.findAll(); 
    model.addAttribute("categories", categories); 
    return "index"; 
} 

私は(:各= "カテゴリ:番目Thymeleafを使用して、何の問題を${categories}")すべてのカテゴリを表示する必要がなく、 JavaScriptで変数 'c​​ategories'にアクセスするにはどうすればいいですか?また、新しい要素を追加してプロパティを設定する方法はJavaScriptでどうすればいいですか? ?

答えて

1

あなたはこの方法あなたがAPIを作成する必要が

// using jquery 
$.ajax({ 
    url:'/', 
    success:function(response){ 
     // get the return pf the method here 
     // can be assigned to any variable 
    } 

javaメソッドの変更

@RequestMapping(path = "/", method = RequestMethod.GET) 
public String showAllCategories(Model model) { 
    //rest of code 
    return (the value which which you want to assign to model property); 
} 

Explore more about ajax

1

へのAJAX呼び出しを行うことができます。例えば、Restである。 考え方は、javacriptで呼び出し可能なメソッド(例えば、AJAX経由)を作成し、javaで行う必要のある操作を実行することです。ここで

あなたは、いくつかの擬似コードを持っている:

あなたが Modelを使用するために、ときに直接 JSONとしてオブジェクトにアクセスすることができますしたいのはなぜ
@RequestMapping(path = "/addCategory", method = RequestMethod.GET) 
public boolean AddCategory(Model model) { 
    //Do your logic to add category 

    if (/*everything went good*/) return true; 
    else return fale; 
} 
1

:?アンギュラ使用

JSスニペット:

$http.get('/app/get').then(function(response) { 
     $scope.categoryList = response.data; 
}, function(response) { 
}); 

JS Snippet using Jquery:

$.ajax({ 
     url: "/app/get", 
     type: 'GET', 
     success: function(response) { 
     var categoryList = response.data; 
     console.log(categoryList); 
     } 
}); 

のJavaスニペット:

@RestController 
@RequestMapping 
public class Controller { 

@RequestMapping(path = "/get", method = RequestMethod.GET) 
public List <Category> showAllCategories() { 
    return categoryService.findAll(); 
} 
} 
関連する問題