【发布时间】:2021-10-30 11:33:56
【问题描述】:
如何在 Wordpress 中使用 Ajax 将 Javascript 对象传递给 PHP?
下面的代码返回 0,而不是对象。缺少什么以便我可以使用 PHP 文件中的金额值?
JS
jQuery(document).ready(function ($) {
var whatever = {
amount: 1234,
};
whatever = JSON.stringify(whatever);
var data = {
action: "my_action",
whatever: whatever,
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function (response) {
alert("Got this from the server: " + response);
});
});
PHP
function my_action()
{
global $wpdb; // this is how you get access to the database
$whatever = intval($_POST['whatever']);
$whatever = json_decode($whatever);
// $whatever += 10;
echo $whatever;
wp_die(); // this is required to terminate immediately and return a proper response
}
【问题讨论】:
-
您正试图通过执行
$whatever = intval($_POST['whatever']);将whatever值{ amount: 1234 }转换为整数。您应该先使用$whatever = json_decode($_POST['whatever']);,然后获取$whatever["amount"]的值并使用$whatever = intval($whatever["amount"])将其转换为整数 -
谢谢。我实际上不需要
intval(),我想访问PHP 中的对象。不过,根据您的建议,它会返回NULL。 -
如果我在 json_decode() 之前回显 $whatever,它会返回字符串
{\"amount\":1234}。 json_decode() 之后变成null.
标签: javascript php jquery ajax wordpress