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

发布于 2024-10-20 06:37:00 字数 2600 浏览 3 评论 0原文

我知道这在“技术上”是无法完成的,因为 AJAX 是异步的,但我正在开发的一个应用程序有很多 AJAX API 调用,我正在尝试使其可以为未来的前端开发人员扩展。

我知道你可以将所有内容都嵌套在回调中,但这会非常丑陋,更不用说下一个想要扩展它的开发人员不知道该怎么做。

因此,例如,这是我的代码(当然,它不起作用,只是返回未定义,但这里是我想要的示例逻辑上工作):

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;
  });
}

稍后开发人员可能想以这种方式使用它: $('div').html('');

我怎样才能让这个工作像这样呢?我可以使用一些 JS 技巧吗?还是我创建的每个函数都必须有一个像 getCategories('html',function(){}) 这样的回调?

如果一切都需要回调,那么对于制作一个带有大量 AJAX 调用的主要 JS 应用程序,您有什么建议可以轻松扩展吗?

更新

根据请求,如果开发人员想要对标签、类别和帖子进行某些操作,这对他来说将是一件痛苦的事情:

//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

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.

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):

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>');

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(){})?

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人心善变 2024-10-27 06:37:00

关于你的例子。

代码中有三个 ajax 请求,它们都不相互依赖。因此,没有理由按顺序执行它们。

至于goGet,它也可以轻松回调。

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

如果你想在所有数据加载后执行代码,你可以在里面使用计数器。

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
    }
});

您可以概括此回调函数,而不是多次声明它。

更简单一点:顺序获取数据。

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

Regarding your examples.

You have three ajax requests in the code and none of them are dependent on each other. So, no reason to execute them sequentially.

As for goGet, it can also take callback easily.

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
    });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文