有没有一个JavaScript API?如何访问JS中的公有数据和私有数据?

时间:2014-10-24 作者:stackoverclan

根据this post Wordpress没有内置的JavaScript API。因此,想要在AJAX上构建的开发人员似乎想出了他们自己的解决方案,但我觉得这并不合适。

除了使用内置API获取帖子或任何数据之外,我真正错过的是一组处理后端和前端接口的JavaScript函数。现在,关于这个问题有什么计划吗?

例如,我很想知道

左侧主菜单被折叠,用户登录的是哪个组,甚至是浏览器等客户端数据。

4 个回复
最合适的回答,由SO网友:gmazzap 整理而成

TL;DR

There is no JavaScript API in the WordPress core and no one is planned, but actually, there is no need of it.

Backend

First of all let\'s say that, regarding the backend, some useful information can be fetched from already present JavaScript global variables (WordPress loves all global flavors).

E.g.

  • ajaxurl for the admin-ajax.php url to be used in ajax calls
  • pagenow for current admin page slug, e.g. \'dashboard\'
  • adminpage for current admin page file, e.g. \'index-php\' (dots are replaced with hiphens)
  • typenow for current post type while in edit.php, post.php or post-new.php
  • userSettings can be used to get information oc current logged user

Those information gives you some "context" of the application state while you are in the backend.

For other things mentioned in the question, you don\'t need any "API", because super-simple jQuery functions can do the trick. For e.g. to know if the admin menu is closed you can check for the "folded" class in body:

if ( $(body).hasClass(\'folded\') ) {
  alert( \'Admin left menu is closed!\' );
} else {
  alert( \'Admin left menu is open!\' );
}

Documentation Lack

For things like the previous snippets it isn\'t worth to create functions. WP already has too many functions in PHP. I really hope that additional functions like those will not be added to core.

What JavaScript in WordPress really needs is more documentation for existing features: none of the things I have written above are documented in any official docs like the Codex or in source files.

Frontend?

Until here I\'ve only talked about the backend.

This is because pretty much all the things that happen on the frontend are related to the theme currently in use. Let\'s imagine there is a JavaScript file provided by WordPress containing functions to get information about the current application state; if a theme doesn\'t enqueue that JS file, those functions are not available and to force a theme to enqueue such a script would be absolutely wrong.

No need of (another) API

However, in WordPress, every information you can get via PHP can be easily used in JavaScript too and without any AJAX request. That function that makes this possible is wp_localize_script().

Let\'s assume you want to get the current user and user data like its user-role in your JavaScript and you also want to know the query variables used in current page, the you can do the following:

$data = array(
  \'user\'       => wp_get_current_user(),
  \'query_vars\' => $GLOBALS[\'wp\']->query_vars
);

wp_localize_script( \'myscript\', \'MyScriptData\', $data );

Doing so in your script, the MyScriptData.user variable will be a JavaScript object with all the users information all the query variables.

This is valid for backend and frontend scripts (in other words: for both "sides"). There is no need for any additional JavaScript API just to fetch that information. PHP is enough if you use the proper ways to pass information from PHP to JS.

Backbone.js

Backbone.js, is a JavaScript framework that allows a (sort of) MVC development pattern with JavaScript. It was included in core with WP 3.5 - mainly to handle the media gallery.

This library is not a WordPress JavaScript API, because surely it allows a more powerful JavaScript development, but not a single WordPress-specific functions has been added to that library and it is the only current core usage of Backbone.js. The media library is more or less undocumented and has no public API. And AFAIK it is not planned to filled that gap. (More than happy to change/remove that statement - if someone can prove me wrong).

WP-API

As pointed out by Rarst and Brian Fegter, the WP API is going to be part of core (probably starting with WP 4.1).

But I have to say that it is not a JavaScript API. It just allows to connect a HTTP request to an application endpoint which is controlled by the WP-API. And the API fetches data from the database and returns it JSON formatted there. Example from the docs:

Want to get your site’s posts? Simply send a GET request to /wp-json/posts. Update user with ID 4? Send a POST request to /wp-json/users/4. Get all posts with the search term “awesome”? GET /wp-json/posts?filter[s]=awesome.

As HTTP requests and related JSON responses can be handled with any language that supports HTTP requests and JSON data format (among them PHP, Ruby, Python, ASP, etc.), the WP API main aim is to allow to get and set WordPress data from non-WP applications. That means from inside any application, not only WordPress.

Sure, since JavaScript is a language that can handle both HTTP requests and JSON format, you can use the WP-API from within WordPress JavaScript too. Someone is also working on a WP js client for that API, but

  • using wp_enqueue_script() + the Ajax API + WordPress PHP functions it is possible to retrieve all the information you need without any additional API. And since all the three "ingredients" are WP established standards, using them is not an "own solution". It just makes use of standard solutions to do custom (and common) tasks, which is what this plugins development is all about.

  • it even is possible to use JavaScript to utilize the WP API. Just because the WP-API returns JSON, it does not make it a JavaScript API. There is no JavaScript function involved (a HTTP request is sent and a JSON reposnse is returned. Pretty much the same as what happens by using the AJAX API). Otherwise any service that returns JSON should be considered a WordPress JS API. The WP-API should be considered an external service API that returns JSON, and it may be the case that the site which consumes this JSON service is the same which provides it.

  • there isn\'t a single thing that can be done with WP API that can not also be done by using the AJAX API. But there are a lot of things that can be done with the AJAX API. but not with the WP-API.

A note on the WP-API + Backbone.js

With Backbone.js, it is possible to get and save information in applications that support RESTful HTTP requests.

The problem is that WordPress, both in "regular" requests and in AJAX ones, is all but RESTful: It only supports $_GET and $_POST requests per default, and using the one or the other with the same URl ends up in ... the same result.

On the contrary, the WP API is RESTful, so Backbone-based applications can take advantage of it for powerful JavaScript applications, but I would stay away from defining Backbone or WP API or Backbone + WP API as a JavaScript API for WordPress for things said above.

SO网友:Brian Fegter

围绕JSON REST API进行了大量开发merged into the 4.1 release. 我相信它将被正式命名为“WP API”。您现在可以开始使用代码库并跟上最新的发展here 直到它到达核心。Ryan McCue和团队已经充实了一些非常好的文档here.

SO网友:Rarst

虽然历史上WP一直以后端为中心,但多年来一直有关于转向大量使用JS的声明。考虑到向后兼容性的承诺,JS很快就会实现对等或接管PHP是值得怀疑的(在我看来),但在这方面已经取得了一些进展。

WordPress管理员现在附带了主干和下划线,这是最新媒体库迭代的主要部分。不幸的是,实现的细节没有严格的文档化,第三方的使用也相对不受欢迎。

REST API 插件正在开发为“feature plugin” 官方打算在未来加入WordPress核心。

SO网友:kaiser

要回答您的陈述:

[…]Wordpress没有内置的Javascript API。因此,想要在Ajax上构建的开发人员似乎想出了他们自己的解决方案,但我觉得这并不合适。

没有“自己的解决方案”可以做。您可以通过使用ATP with ajax_template_part() 通过@G.M. 或者类似的插件,走捷径,但在WordPress中仍然没有使用AJAX的非标准方法。那些“自己的解决方案”/(大部分)是做错了。AJAX调用(大致)是这样完成的:

在上下文感知挂钩(公共或私有/登录)上注册AJAX回调$.ajax() 以及类似的功能来对用户交互做出反应。使用全局(本地化)JS对象将数据传递回PHP回调wp_send_json_success() 和类似功能如果插件或主题不是这样做的,那么作者就没有阅读内容或没有查看示例。这里有一个应该使用的框架。

More and detailed info about how to handle AJAX in WP can be found in the community book "WordPressTheRightWay".

除了使用内置API获取帖子或任何数据之外,我真正错过的是一组处理后端和前端接口的Javascript函数。[…]例如,我想知道左边的主菜单已经折叠,或者哪个用户登录了,或者他是哪个组,甚至是浏览器之类的客户端数据。

WordPress并没有明确说明您需要用AJAX做什么。这就是为什么您可以将几乎所有内容都塞进一个本地化/全球化的数组中,并将其用于AJAX调用。这与主干网的工作原理完全一致:你必须做你喜欢的事情,你想做的事情。

如果您想使用一些固执己见的JavaScript MVC框架,比如AngularJs,那么您就错了。还有其他CMS,如十月CMS、Drupal8等,更能为其提供基础。WordPress将要求您构建一组自定义的重写端点,您可以在其中返回JS控制器的数据集。

结束