所以我正在制作一个 WordPress 网站,并希望将数据(由 jQuery 动态创建的 CSS 样式)发送到 PHP。这样做的原因(与这个问题不完全相关)是将数据编写为在每个页面开头加载的 .css 文件,这样在 js 执行时就不会出现可见的样式“变化”(嗯,仅在第一次加载页面时)。我确信可能有更好的方法来做到这一点。
回到主要部分(将数据从 jQuery 发送到 .php)。我正在执行一个 js 脚本(在“front-page.php”上),它执行以下操作:
jQuery(function($){
$(window).on("load", function() {
$.ajax({
type: "POST",
url: "create-style.php",
data: { style : styleString },
dataType: "json",
success: function () {
console.log("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");
},
});
}
});
关于php - 使用 $.ajax 向 PHP 传递数据会使 $_POST 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39240284/