【问题标题】:How to pass Javascript Object to PHP with Ajax in Wordpress如何在 Wordpress 中使用 Ajax 将 Javascript 对象传递给 PHP
【发布时间】: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


【解决方案1】:

你的 PHP 有问题,试试这个:

function my_action()
{
    global $wpdb; // this is how you get access to the database

    $whatever = $_POST['whatever'];
    $whatever = json_decode($whatever);
    $amount = intval($whatever['amount']); 

    echo $amount;

    wp_die(); 
}

【讨论】:

  • 谢谢。我实际上不需要intval(),我想访问 PHP 中的对象。不过,根据您的建议,它会返回 NULL
  • 如果我在 json_decode() 之前回显 $whatever,它会返回字符串 {\"amount\":1234}。 json_decode() 之后变成null.
猜你喜欢
  • 2012-10-17
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-18
相关资源
最近更新 更多