使用$传递数据.ajax到PHP的$_POST为空


Passing data using $.ajax to PHP leaves $_POST empty

所以我正在制作一个Wordpress网站,并希望将数据(css样式动态创建的jQuery)发送到PHP。这样做的原因(与这个问题不完全相关)是将数据写成一个.css文件,在每个页面的开头加载——这样当js执行时(好吧,只有第一次加载页面)就不会有明显的样式变化。我肯定会有更好的办法。

回到主要部分(将数据从jQuery发送到.php)。我正在执行一个js脚本(在"首页。php"上),它这样做:

jQuery(function($){
    $(window).on("load", function() { 
        $.ajax({
            type: "POST",
            url: "create-style.php",
            data: { style : styleString }, 
            dataType: "json",
            success: function () {
                console.log("success");
            }
        });
    });
});

控制台显示'success',所以我假设数据正在传递给create-style.php。

create-style.php的write函数执行此操作

 $file = 'new-style.css';
 $style = $_POST['style'];
 file_put_contents($file, $style, LOCK_EX);

现在我尝试的第一件事是将函数包含在Wordpress的functions.php中。我不太了解Wordpress或一般的web开发,但这似乎是直观的,这不会工作,因为可能php文件在js之前执行(所以它怎么能得到数据?)

为了解决这个问题,我将create-style.php重写为cron,使用wp_schedule_single_event在有人访问该网站时触发,有轻微延迟:

add_action('write_style_cron', function(){
    // the above writing function
});
wp_schedule_single_event(time() + 10, 'write_style_cron'); // give it a slight delay to make sure jQuery happens

然而,没有$_POST数据被写入文件,做任何测试都显示它是空的。我做了很多测试,知道:

  • cron功能基本工作
    • 写入功能与测试值一起工作
  • $_POST显示为完全空,我在/wp-cron.php?doing_wp_cron
  • 中得到一个"未定义的索引"错误
  • $。ajax正在触发success
  • 没有其他php/js错误

感谢您阅读这篇很长的文章。我一整天都在网上搜索解决方案,我觉得最好还是直接问吧。

试试下面的代码:

jQuery(function(){
$('#yourFormName').on('submit', function (e) { //on submit function
    e.preventDefault();
    $.ajax({
      type: 'post', //method POST
      url: 'create-style.php', //URL of page where to pass values
      data: $('#yourFormName').serialize(), //seriallize is passing all inputs values of form
      success: function(){ 
              console.log("success");
                  },
    });
}
});