我如何进行初始JavaScript Ajax初始化?

时间:2017-06-01 06:24:39

标签: javascript jquery ajax knockout.js

我正在用ajax提取信息。我想要我的document.ready函数(ajax)首先启动,因为首先启动knockout文件而我的“var initialData”值为null。我的Ajax如何首先开始?

Here is my F12 Source

我的剧本:

<script type="text/javascript">
        var initialData;
        function functionViewModel() {
                $(document).ready(function () {
                    $.ajax({
                        type: "POST",
                        url: "KnockoutGrid2.aspx/GonderUrunler",
                        data: "{}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg) {
                            console.log(msg.d);
                            initialData = msg.d;
                        }
                    });
                });
            var fn = {
                friends: ko.observableArray(initialData)
            };
            fn.removeUser = function (item) {
                fn.friends.remove(item);
            };
            return fn;
        };
        ko.applyBindings(functionViewModel());
    </script>

3 个答案:

答案 0 :(得分:1)

更新2 @ user3297291的答案比我的好,因为Knockout处理这个表单的所有状态。请不要在ajax请求的答案中执行NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier]; NSString *appStoreURL = [@"http://itunes.apple.com/lookup?bundleId="stringByAppendingString:bundleIdentifier]; // Get the main bundle of the app so that we can determine the app's version number NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary]; NSString *appVersion = [infoDict objectForKey:@"CFBundleShortVersionString"]; // example: 1.0.0 NSData *dict = [NSData dataWithContentsOfURL:[NSURL URLWithString:appStoreURL]]; NSError* error; NSDictionary* json = [NSJSONSerialization JSONObjectWithData:dictoptions:kNilOptions error:&error]; NSLog(@"%@", json);

用户需要知道数据尚未加载,这可以通过淘汰来处理。

原始回答

也许如果你在applybindings函数中移动Knockout的初始化:

success

您可以使用以下消息显示div:“正在加载数据......”。

<script type="text/javascript"> $(document).ready(function () { $.ajax({ type: "POST", url: "KnockoutGrid2.aspx/GonderUrunler", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { console.log(msg.d); initialData = msg.d; // All initialization inside the 'success' function function functionViewModel(initialData) { var fn = { friends: ko.observableArray(initialData) }; fn.removeUser = function (item) { fn.friends.remove(item); }; return fn; }; ko.applyBindings(functionViewModel(initialData)); } }); }); </script> 运行时,隐藏此div。

更新1 在您发表评论后,我不知道您为什么需要success。我提出这个解决方案:

return fn

我在这里使用 <script type="text/javascript"> // Updating 'functionViewModel()' to add 'self'. // Move functionViewModel()' outside ajax response function functionViewModel(initialData) { var self = this; self.friends = ko.observableArray(initialData); self.removeUser = function (item) { self.friends.remove(item); }; }; $(document).ready(function () { $.ajax({ type: "POST", url: "KnockoutGrid2.aspx/GonderUrunler", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { console.log(msg.d); initialData = msg.d; // All initialization inside the 'success' function ko.applyBindings(functionViewModel(initialData)); } }); }); </script> (请参阅Managing ‘this’)并且不返回self,因为Knockout处理其状态。

答案 1 :(得分:1)

希望等待applyBindings直到你的ajax响应被处理...如果你让淘汰赛等待应用绑定并且你的用户将什么都没有,那么你的文档看起来会很难看看看。

应该做什么:

  • $(document).ready触发
  • 后立即应用绑定
  • 确保您的视图模型使用observable属性,以便您以后轻松注入数据
  • 确保您定义某种加载状态以向您的用户显示正在下载的数据

即:

function functionViewModel() {
  var friends = ko.observableArray([]);
  var loading = ko.observable(true);
  var removeUser = function(user) {
    friends.remove(user);
  }
  
  // Get the data and write it to an observable property once done
  $.ajax({
    type: "POST",
    url: "KnockoutGrid2.aspx/GonderUrunler",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      friends(JSON.parse(msg.d));
      loading(false);
    }
  });
    
  return {
    friends: friends,
    loading: loading,
    removeUser: removeUser
  };
};

$(document).ready(function() {
  ko.applyBindings(functionViewModel());
});

答案 2 :(得分:0)

在代码中使用async:false

                   $.ajax({
                        type: "POST",
                        url: "KnockoutGrid2.aspx/GonderUrunler",
                        data: "{}",
                        async : false,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg) {
                            console.log(msg.d);
                            initialData = msg.d;
                        }
                    });