Knockout JS - >使用新GET调用的值更新视图

时间:2013-11-13 17:38:20

标签: api jquery post knockout.js get

我正在使用网络服务。我正在进行GET调用以获取所有问题 - >用户将回答该问题并使用后调用发布。这部分现在按预期工作。现在,我想在POST呼叫成功后立即拨打另一个GET电话。我可以在POST调用完成后进行GET调用,但是视图仍然显示来自旧GET调用的数据。如何使用来自新GET调用的信息更新视图。

GET - > POST - >新GET(此次调用中未更新数据。)

JSON

{
   "Respondent_ID":"hello111",
   "Group_Name":"",
   "Product_ID":80,
   "Language_ID":1,
   "First_Name":"hello",
   "Last_Name":"111",
   "Respondent_EMail":"",
   "Gender":"M",
   "AllQuestions":[
      {
         "Question_Number":76,
         "Question_Text":"I think ",
         "Definition":"",
         "Answer":0
      },
      {
         "Question_Number":77,
         "Question_Text":"I am ",
         "Definition":"",
         "Answer":0
      },
      {
         "Question_Number":78,
         "Question_Text":"I am mild mannered",
         "Definition":"",
         "Answer":0
      },
      {
         "Question_Number":79,
         "Question_Text":"I am strong",
         "Definition":"",
         "Answer":0
      },
      {
         "Question_Number":80,
         "Question_Text":"I am a risk taker",
         "Definition":"",
         "Answer":0
      }
   ],
   "AnswerChoice":[
      {
         "Answer_Choice":"Strongly disagree",
         "Answer_Choice_Value":1
      },
      {
         "Answer_Choice":"Disagree",
         "Answer_Choice_Value":2
      },
      {
         "Answer_Choice":"Neutral",
         "Answer_Choice_Value":3
      },
      {
         "Answer_Choice":"Agree",
         "Answer_Choice_Value":4
      },
      {
         "Answer_Choice":"Strongly agree",
         "Answer_Choice_Value":5
      }
   ]
}

-

 @{
        ViewBag.Title = "Questions";
    }

    <html>
    <body>       
    <script src="~/Scripts/knockout.mapping-latest.js"></script>             
    <script>       
       function GetAllEmployees() {              
            $.ajax({
                url: '/api/Questions?respondent_id=hello111',
                type: 'GET',
                dataType: 'json',
                success: function (data) {                   
                    var data2 = data.AllQuestions;        
                    var viewModel = {
                        data: ko.mapping.fromJS(data2),
                        Question_Number: ko.observable(data.AllQuestions[0].Question_Number),
                        Question_Text: ko.observable(data.AllQuestions[0].Question_Text),                    

                        save: function () {
                            $.ajax({
                                url: '/api/lms',
                                type: 'POST',                      
                                data: data, 
                                dataType: 'json',
                                success: function (data) {                              
                                    $.ajax({
                                        url: '/api/Questions?respondent_id=hello111',
                                        type: 'GET',
                                        dataType: 'json',
                                        success: function (data) {
                                            //How can update the view with the new data I got from the get call. 
                                            }

                                            ko.applyBindings(viewModel);
                                        }
                                    });        

                                },
                                error: function (x, y, z) {
                                    alert(x + '\n' + y + '\n' + z);
                                }
                            });
                        }       
                    }                       

                     ko.applyBindings(viewModel);     

                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }         

    </script>              

    </body>
    </html>       
            <a href="javascript:GetAllEmployees();"> Get Questions</a>       
            <form data-bind="submit: save">
    <table>
    <thead>
          <tr><th>#</th>Question<th>Strongly disagree</th><th>Strongly disagree</th><th>Disagree</th><th>Neutral</th><th>Agree</th><th>Strongly agree</th></tr>
               </thead>              
            <tbody data-bind="foreach: $data">
      <tr>
            <td>
                <span data-bind="text: Question_Number"></span>
            </td>
            <td>
                <span data-bind="text: Question_Text"></span>
            </td>

          <td><input type="radio" class="radio" value="1" data-bind="attr: { name: Question_Number}"></td>

           <td><input type="radio" class="radio" value="2" data-bind="attr: { name: Question_Number }"></td>
            <td><input type="radio" class="radio" value="3" data-bind="attr: { name: Question_Number }"></td>
            <td><input type="radio" class="radio" value="4" data-bind="attr: { name: Question_Number }"></td>
            <td><input type="radio" class="radio" value="5" data-bind="attr: { name: Question_Number }"></td>
                </tr>
    </tbody>
    </table>
         <button type="submit">Go</button>
        </form>

1 个答案:

答案 0 :(得分:0)

您必须取消嵌套代码。

您应该开始使用jQuery的原生.get().post()来电和延期回调(.then().done().fail().always() )用于Ajax处理。

我重写了你的JS代码:

function showAjaxError(x, y, z) {
    alert(x + '\n' + y + '\n' + z);
}
function QuestionViewModel(respondentId) {
    var self = this;

    self.data = ko.observableArray();
    self.currentQuestionId = ko.observable();
    self.currentQuestion = ko.computed(function () {
        return self.data()[self.currentQuestionId()];
    });

    self.mapQuestions = function (rawData) {
        return ko.mapping.fromJS(rawData.AllQuestions);
    };
    self.rewind = function () {
        self.currentQuestionId(0);
    };
    self.updateFromServer = function () {
        $.get('/api/Questions', { respondent_id: respondentId })
        .then(self.mapQuestions)
        .done(self.data)
        .done(self.rewind)
        .fail(showAjaxError);
    };
    self.save = function () {
        $.post('/api/lms', { data: ko.mapping.toJS(self.data) })
        .done(self.updateFromServer)
        .fail(showAjaxError);
    };

    self.updateFromServer();
}

ko.applyBindings(new QuestionViewModel('hello111'));

注释

  • '/api/Questions?respondent_id=hello111'不应该是硬编码的。把它变成一个变量。
  • 查看模型在使用构造函数构建时效果最佳,因为否则很难让它们在内部引用它们。
  • 不要重复自己。制作小型,可重复使用的功能(如showAjaxError())并重复使用它们。如果您的代码深度超过3级,则表示您做错了。
  • 通过普遍接受的编码样式约定,非构造函数的所有内容都以小写字母开头,名称没有下划线(例如questionText而不是Question_Text)。