Wordpress admin-ajax.php returns 0 和 POST 上的状态 400,但适用于 GET
Wordpress admin-ajax.php returns 0 and status 400 on POST, works on GET though
我已将 angular 应用程序嵌入到 iframe 中的 Wordpress 站点。
Angular 应用试图触发子主题中function.php 文件中注册的Wordpress 操作,代码如下:
angular_app.js
this.http.post('/wp-admin/admin-ajax.php', {action: 'my_sendmail', data: 'whatever'}).subscribe((response) => {
console.log(response);
});
function.php
add_action( 'wp_ajax_my_sendmail', 'my_sendmail_function' );
add_action( 'wp_ajax_nopriv_my_sendmail', 'my_sendmail_function' );
function my_sendmail_function() {
wp_send_json(array('resp' => 'Hello World!'));
wp_die();
}
以上方法无效。有趣的是,当我将 JS 代码更改为:
this.http.get('/wp-admin/admin-ajax.php?action=my_sendmail').subscribe((response) => {
console.log(response);
});
它有效,但是我确实需要将其设为 POST,因为我需要 post 请求中的大量数据。有人知道这里发生了什么吗?
最后我离开了尝试让它工作。我使用不同的可用机制解决了它。在 function.php 我创建了新的休息端点:
add_action( 'rest_api_init', function() {
register_rest_route("as/api", "sendmail", array(
'methods' => 'POST',
'callback' => 'my_sendmail_function'
));
});
function my_sendmail_function() {
...email setup;
wp_main($to, $subject, $body, $headers);
}
在 FE 上,在我的 Angular 应用程序中:
this.http.post(location.origin + '/wp-json/as/api/sendmail', data).subscribe((response) => {
console.log(response);
});
效果很好。
我已将 angular 应用程序嵌入到 iframe 中的 Wordpress 站点。
Angular 应用试图触发子主题中function.php 文件中注册的Wordpress 操作,代码如下:
angular_app.js
this.http.post('/wp-admin/admin-ajax.php', {action: 'my_sendmail', data: 'whatever'}).subscribe((response) => {
console.log(response);
});
function.php
add_action( 'wp_ajax_my_sendmail', 'my_sendmail_function' );
add_action( 'wp_ajax_nopriv_my_sendmail', 'my_sendmail_function' );
function my_sendmail_function() {
wp_send_json(array('resp' => 'Hello World!'));
wp_die();
}
以上方法无效。有趣的是,当我将 JS 代码更改为:
this.http.get('/wp-admin/admin-ajax.php?action=my_sendmail').subscribe((response) => {
console.log(response);
});
它有效,但是我确实需要将其设为 POST,因为我需要 post 请求中的大量数据。有人知道这里发生了什么吗?
最后我离开了尝试让它工作。我使用不同的可用机制解决了它。在 function.php 我创建了新的休息端点:
add_action( 'rest_api_init', function() {
register_rest_route("as/api", "sendmail", array(
'methods' => 'POST',
'callback' => 'my_sendmail_function'
));
});
function my_sendmail_function() {
...email setup;
wp_main($to, $subject, $body, $headers);
}
在 FE 上,在我的 Angular 应用程序中:
this.http.post(location.origin + '/wp-json/as/api/sendmail', data).subscribe((response) => {
console.log(response);
});
效果很好。