Backbone.js 提取不返回任何内容

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

我尝试创建一个简单的从servlet获取数据的 Backbone.js 模型示例。
我有这个:

require(["backbone"],function(Backbone)

var myDataModel = new (Backbone.Model.extend({

    initialize:function(){
        this.set({title:"My First Backbone",data:new Date()});
    },

    setTitle:function(title){       
        this.set({title:title});        
    },

    setData:function(data){     
        this.set({data:data});      
    },

    getTitle:function(){        
        return this.get("title");       
    }, 

    getData:function(){     
        return this.get("data");        
    },
    url:"http://........../BackboneApp/Todo",

    parse:function(response,xhr){

        console.log(response);

    }

}));

myDataModel.fetch().done(function(s){console.log(s)});

我servlet是这样的:

public class TodoServlet extends HttpServlet  {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String text = "{id:1,title:'harry',data:'sdsd'}";
    response.setContentType("application/json");  // Set content type of the response so that jQuery knows what it can expect.

    response.getWriter().write(text);       // Write response body.
}

}

模型中的parse函数不执行,done方法也不执行,但是fail方法可以正常工作,返回响应对象。

aor9mmx1

aor9mmx11#

您的JSON字符串无效。它应该是

"{"id":1,"title":"harry","data":"sdsd"}"

此外,还要确保根据操作结果返回成功的HTTP状态代码,否则将调用错误回调。

相关问题