无法从控制器访问 Backbone.js 模型属性

wbgh16ku  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(128)

我遇到了一个关于BackboneJS和spring mvc控制器之间交互的错误。我无法在将模型添加到集合列表时访问模型属性。我的JS代码中容易出错的部分如下:

var Task = Backbone.Model.extend({
   defaults: {
     taskName: '',
     category:'',
     completed: false,
     dateCreated:0,
     dateCompleted:0
   }
 });

var TaskList = Backbone.Collection.extend({
   model: Task,
   url : "/todoCollection"
 });

// instance of the Collection
var taskList = new TaskList();

var TaskView = Backbone.View.extend({

   tagName: 'div',
   render: function(){

       var itemHTML = _.template($('script.itemview').html());

     this.$el.html(itemHTML(this.model.toJSON()));
     return this; // enable chained calls
   }

});

 var TaskCreateView = Backbone.View.extend({
     el : ".taskcreate",
     initialize : function(){
         this.render();
         this.input = this.$('#taskInput');
         this.categoryInput = this.$('#taskCategory');
         taskList.on('add', this.addAll, this);
         taskList.on('reset', this.addAll, this);
         taskList.fetch();
     },

     render : function(){
         var createListHTML = _.template($('script.create-task-view').html());
         this.$el.append(createListHTML);
         var createListHTML = _.template($('script.list-view').html());
         this.$el.append(createListHTML);
     },

     events: {
         'click button#createButton':'createTask'
     },

     createTask : function(e){

         if(this.input.val() == ''){
            alert("Task name expected");
            return;
         }

         if(this.categoryInput.val() == 'None'){
            alert("Enter valid category");
            return;
          }

         var newTask = {

             taskName: this.input.val().trim(),
             completed: false,
             category: this.categoryInput.val().trim()

         };

         taskList.create(newTask,{ wait: true });
         this.input.val(''); // clean input box
         this.categoryInput.val('None');

     },

     addOne: function(task){
         var view = new TaskView({model: task});
         $('#listDiv').append(view.render().el);
     },

     addAll: function(){
         this.$('#listDiv').html(''); // clean the todo list
         taskList.each(this.addOne, this);
     }

});

var TodoAppView = Backbone.View.extend({

    el: '#todoApp',

    initialize : function(){
      this.render();
    },

    render : function(){
        var appHTML = _.template($('script.appview').html());
        this.$el.append(appHTML);
        var taskCreateView = new TaskCreateView();
    }

});

var TodoApp1 = new TodoAppView();

TaskList中的url**/todoCollection**Map到定义如下的Spring mvc控制器:

package com.glider.controller;

import com.glider.model.Todo;
import com.glider.service.TodoService;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
public class TodoCollectionController {

    @Autowired
    TodoService service;

    @RequestMapping(value = "/todoCollection",method = RequestMethod.POST)
    @ResponseBody
    public String createTodo(@RequestParam(value = "taskName")String taskName,
                          @RequestParam(value = "category")String category){

        System.out.println("Method working");
        ObjectMapper objectMapper = new ObjectMapper();
        try {

            Todo todo =  service.create(taskName,category);
            String jsonInString = objectMapper.writeValueAsString(todo);
            return jsonInString;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";

    }

    @RequestMapping(value = "/todoCollection",method = RequestMethod.GET)
    @ResponseBody
    public String getAllTodo(){

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<Todo> todoList = service.findAllTasks();
            String jsonInString = objectMapper.writeValueAsString(todoList);
            return jsonInString;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";

    }

}

控制器方法createTodo需要类似taskNamecategory的参数。将新的task添加到taskList时也会提到这些属性。在服务器上执行上述代码时,我从浏览器控制台收到一个错误,定义如下:

jquery.min.js:4 POST http://localhost:8080/todoCollection 400 (Bad Request)

服务器端存在如下错误:

HTTP Status 400 - Required String parameter 'taskName' is not present.

我无法解决此问题。

ztmd8pv5

ztmd8pv51#

您需要一个Java类来表示spring可以将值Map到的JSON对象。@RequestParam用于Map来自请求的查询字符串参数,而REST和 Backbone.js 则不是这样。
您的代码应类似于:

public String createTodo(@RequestBody Todo todo)){}

spring将根据JSON请求设置todo中的值

相关问题