简体   繁体   中英

Backbone.js fetch method is not working

I am fairly new to Backbone.js and I am trying to understand how it works to get data and post data to a REST api. In the code below in Codeigniter I am trying to to fetch data from my REST api that is returning a json object. Using an input field and a submit button, I am trying to pass the value to the controller function that should return the json data if the data is found in the database model. From what I have understood, when calling fetch() the URL should change, but nothing happens when I press the button submit. Although if I manually enter a url in this format: http://localhost/Codeigniter/index.php/testcontroller/getdatabasedata?searchvalue=Rome I do get back the jason data. What I need to do to submit the value from the input field to the controller function and display the results?

Thank you

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>

<script language="Javascript">
    $(document).ready(function () {
      var TodoItem = Backbone.Model.extend({
        url: function () {
          var urlstr = "../../index.php/testcontroller/getdatabasedata?searchvalue="+this.get("name");
          return urlstr;
        },
        defaults: {
          name: null,

        }
      });

      var todoitem = new TodoItem();
      var TodoView = Backbone.View.extend(
      {
        el: '#container', 
        model: todoitem,

        initialize: function(){
          this.listenTo(this.model,"sync change", this.gotdata);
        },
        events: {
            "click #submitbtn" : "getdata",

          },
          getdata: function (event) {
            var celebname = $('#celebname').val();

            this.model.set({name:celebname});
            this.model.fetch();
          },
          gotdata: function () {
            var age = this.model.get("age");
            $('#age').html(age);
          },
      });
      var todoView = new TodoView();
});
</script>

事件是否回答了您,当您单击“ #submitbtn”时,您可以在console.log中使用getdata()函数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM