gpt4 book ai didi

javascript - Wordpress update_user_meta onclick 使用 Ajax

转载 作者:行者123 更新时间:2023-11-28 07:39:57 25 4
gpt4 key购买 nike

我正在尝试通过 Wordpress 中的 Ajax 调用 update_user_meta。我不断得到“成功!”控制台日志,但没有返回数据,并且用户元字段没有更新。

单击按钮时的general.js:

var newViewPreference = jQuery(this).attr('id');
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: {
'action':'update_view_pref',
'viewPref' : newViewPreference
},
success:function(data) {
console.log(data);
console.log("success!");
},
error: function(errorThrown){
console.log(errorThrown);
console.log("fail");
}
});

函数.php

add_action( 'wp_ajax_update_view_pref', 'update_view_pref');
function update_view_pref() {
if(empty($_POST) || !isset($_POST)) {
ajaxStatus('error', 'Nothing to update.');
} else {
try {
$user = wp_get_current_user();
$viewPref = $_POST['viewPref'];
if ($viewPref == 'toggle-grid') {
update_user_meta( $user->ID, 'wpcf-shop-view-preference', 'grid' );
} elseif ($viewPref == 'toggle-list') {
update_user_meta( $user->ID, 'wpcf-shop-view-preference', 'list' );
}
die();
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
}

谁能指出我哪里出错了?谢谢。

最佳答案

将 $_POST 更改为 $_REQUEST 有效。

谁能解释一下为什么 $_POST 不起作用而 $_REQUEST 起作用?

我通过单击按钮(而不是表单)将数据提交给 ajax 请求。

关于javascript - Wordpress update_user_meta onclick 使用 Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28180584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com