【问题标题】:Wordpress Ajax can't use POST, can't pass objectWordpress Ajax 不能使用 POST,不能传递对象
【发布时间】:2018-04-04 17:38:25
【问题描述】:

我正在尝试在自定义帖子创建中从管理员后台访问 wordpress ajax。

我尝试发送 POST 请求,但没有结果,服务器回答:0,错误 400。

我试图从 amin_ajax.php 中转储 $_REQUEST,但当我使用它时它是空的:

 $.ajax({
    url : ajaxUrl,
    type : 'POST',
    data : {
      action : "gMapsLatLong",
      adresse : adresse,
      adresse2 : adresse2,
      code_postal : code_postal,
      ville : ville
    },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
  });

我已经尝试过序列化和不序列化数据对象,但都没有结果。 当我尝试使用 GET 时,我只能传递“action”变量,其他变量不存在于请求中。

在我的function.php文件中,我放了:

add_action('wp_ajax_gMapsLatLong', 'gMapsLatLong');
add_action('wp_ajax_nopriv_gMapsLatLong', 'gMapsLatLong');

谁能看到我在这里遗漏的明显东西?

【问题讨论】:

    标签: php ajax wordpress


    【解决方案1】:

    您说过contentType: "application/json; charset=utf-8",,但您传递给data 的值不是JSON。

    不要覆盖 Content-Type 标头(这将导致 PHP 不解析请求正文,因为它不支持 JSON 编码请求)或将 JSON 传递给 data(通过编码 JavaScript 对象使用JSON.stringify)。

    如果您采用后一种方法,那么 PHP 将需要读取原始请求正文并显式解析 JSON。

    【讨论】:

      【解决方案2】:

      当您将 json 发布到 PHP 时,它不会显示在 $_POST 全局中。如果您要发送正常的'application/x-www-form-urlencoded; charset=UTF-8' 帖子,则应删除contentType,然后它将显示在$_POST 中。如果您确实想发布 json,那么您需要这样做:

      $.ajax({
      url : ajaxUrl,
      type : 'POST',
      data : JSON.stringify({
        action : "gMapsLatLong",
        adresse : adresse,
        adresse2 : adresse2,
        code_postal : code_postal,
        ville : ville
      }),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      });
      

      然后在 PHP 中你可以这样做:

      $_JSON = json_decode(file_get_contents('php://input'), true);
      

      【讨论】:

      • 感谢您的快速回答,遗憾的是我仍然得到 400;这可能与我使用 wamp 在 localhost 上有关吗?
      【解决方案3】:

      经过一些尝试和错误,我发现了两个问题:

      jQuery.ajax({
      

      而不是

      $.post({
      

      由于一些愚蠢的误解,我的价值观未定义。 感谢您的阅读!

      【讨论】:

        猜你喜欢
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-17
        • 2013-12-12
        • 2021-02-28
        • 2012-05-13
        相关资源
        最近更新 更多