简体   繁体   English

返回的HTML / JSON与包含jQuery AJAX调用的普通JS函数?

[英]return HTML/JSON with a normal JS function that contains a jQuery AJAX call?

I know this "technically" can't be done as AJAX is async, but an app I'm working on has a lot of AJAX API calls and I'm trying to make this extendable for future front-end devs. 我知道这无法“技术上”地完成,因为AJAX是异步的,但是我正在开发的一个应用程序具有许多AJAX API调用,并且我正在尝试使其可扩展用于将来的前端开发人员。

I know you can just nest everything in callbacks, but that'd be super ugly and not to mention the next dev coming along wanting to extend it wont know what to do. 我知道您可以将所有内容嵌套在回调中,但这将非常丑陋,更不用说下一个想要扩展它的开发人员了,不知道该怎么做。

So, for example, here is my code (that, of course , doesn't work and just returns undefined , but here for an example of how i'd like it to logically work): 因此,例如,这是我的代码( 当然 ,这是行不通的,只是返回undefined ,但是这里是我希望其在逻辑上如何工作的示例):

var getCategories = function(type){
  var categories;
  $.get('/api/categories/all',function(json){
    if(type == 'html'){
      categories = '';
      for(x in json.data){
        categories=categories+'<option id="category_'+json.data[x].category_id+'" title="'+json.data[x].description+'">'+json.data[x].category+'</option>'
      }
    }
    else{ //JSON
      categories = json.data;
    }
    return categories;
  });
}

And later on a dev might want to use it in this way: $('div').html('<select>'+getCategories('html')+'</select>'); 之后,开发人员可能希望以这种方式使用它: $('div').html('<select>'+getCategories('html')+'</select>');

How could I make this work like that? 我该如何做这样的工作? Can I with some JS trick or would every function I make like this HAVE to have a callback like, getCategories('html',function(){}) ? 我可以使用一些JS技巧,还是让我像这样做的每个函数都具有类似getCategories('html',function(){})的回调?

If it's everything needs a callback, do you have any tips on making a mostly JS app w/ lots of AJAX calls easily extendable? 如果所有内容都需要回调,那么您是否有使用大多数可轻松扩展的AJAX调用的JS应用程序的任何技巧?

UPDATE 更新

As per request, this would be a pain in the ass for a developer if he wanted to do something with, lets say, tags, categories, and posts: 根据要求,如果开发人员想做一些标签,类别和帖子,这对于开发人员来说是一件痛苦的事情:

//Some event on click
$('.button').click(function(){
  $.ajax({
    url: "/api/categories/all",
    success: function(json){
      categories = '';
      for(x in json.data){
        categories=categories+'<option id="category_'+json.data[x].category_id+'" title="'+json.data[x].description+'">'+json.data[x].category+'</option>'
      }
      $.ajax({
        url: "/api/tags/all",
        success: function(json){
          tags = '';
          for(x in json.data){
            tags=tags+'<option id="tags_'+json.data[x].category_id+'" title="'+json.data[x].description+'">'+json.data[x].category+'</option>'
          }
          $.ajax({
            url: "/api/posts/all",
            success: function(json){
              posts = '';
              for(x in json.data){
                posts=posts+'<option id="posts_'+json.data[x].category_id+'" title="'+json.data[x].description+'">'+json.data[x].category+'</option>'
              }

              //And so on...
              //after getting all this data that the developer might want
              //to put this in a modal to edit these items...
            }
          });
        }
      });
    }
  });
});
//On load tho, on the same page, he might want to list "popular" categories, tags, all, and he'd
//have to copy and paste the above code but change, all to popular
//Im looking to make a JS API almost to make this simpler, LIKE:
var tags = goGet('tags','popular');
var categories = gotGet('categoties','all');
//etc

Regarding your examples. 关于你的例子。

You have three ajax requests in the code and none of them are dependent on each other. 您的代码中有3个ajax请求,它们都不相互依赖。 So, no reason to execute them sequentially. 因此,没有理由按顺序执行它们。

As for goGet , it can also take callback easily. 至于goGet ,它也可以轻松进行回调。

goGet('tags','popular', function(tags) {
    // do something with tags
});

If you want to execute code after all data loaded, you can use counter inside. 如果要在所有数据加载后执行代码,可以在内部使用计数器。

var tags, categories;
var completed = 0;
goGet('tags','popular', function(entities) {
    tags = entities;
    completed++;
    if (++completed == NUMBER_OF_REQUESTS) {
        // execute your code
    }
});
goGet('categories','popular', function(entities) {
    tags = entities;
    completed++;
    if (++completed == NUMBER_OF_REQUESTS) {
        // execute your code
    }
});

You can generalize this callback function, to not declare it multiple times. 您可以泛化此回调函数,以免多次声明。

A bit simpler: fetch data sequentially. 更简单:依次获取数据。

goGet('tags','popular', function(tags) {
    goGet('categories','popular', function(categories) {
        // execute your code
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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