【问题标题】:How to pass javascript variable to php to store in the database of wordpress?如何将javascript变量传递给php以存储在wordpress的数据库中?
【发布时间】:2017-03-21 09:51:12
【问题描述】:

我正在 wordpress 中构建星级评分系统,因此希望将评分数据存储到 wordpress 数据库。 我将星级 php 作为模板存储在 wordpress 主题文件夹中。这是代码的一部分。

<?php 
/* Template Name: RatingSystem */   
?>

<html>for displaying the stars</html>

<css>for hover and other star rating effects</css>

<script>
var r1;
var r2;
function submitForm() {
$.ajax({
         type: "POST",
         url: 'submit-rating.php',
         data: { r1 : r1 },
         success: function(data)
          {
            alert("success!");
           }
           });
                         }
function RatingValue(rating) 
{r1=rating;}    

function RatingValue1(rating1)
{r2=rating1;}   
</script>

提交评级.php(PHP 文件)。

<?php
if(isset($_POST['r1']))
{
$rating = $_POST['r1'];
echo $rating;
}
?>

但是当我执行 echo $rating 时没有显示输出。为什么?另外请解释如何存储在 wordpress 数据库中。提前致谢。

【问题讨论】:

    标签: javascript php html css ajax


    【解决方案1】:

    您的输出没有显示,因为 JS 不“知道”它应该显示它。 而不是

    function submitForm() {
        $.ajax({
             type: "POST",
             url: 'submit-rating.php',
             data: { r1 : r1 },
             success: function(data)
             {
                alert("success!");
             }
        });                        
    }
    

    试试

    function submitForm() {
        $.ajax({
             type: "POST",
             url: 'submit-rating.php',
             data: { r1 : r1 },
             success: function(data)
             {
                alert(data);
             }
        });                        
    }
    

    function(data) 中的data 是 JS 得到的响应。为了在 div 中显示它,您可以在 alert 所在的位置使用 $('#divID').html(data)

    -- 编辑:忘记了你问题的第二部分。

    我建议您使用 WPDB 在您的 wordpress 数据库中发布您的数据。如果此 PHP 文件是模板的一部分,或者您已关闭该文件的模板引擎并需要 wp_load.php,则这是可能的。如果这些都不适用,我建议您通过在您的 php 文件顶部包含它来执行后者

    // Include WordPress
    define('WP_USE_THEMES', false);
    require_once('PATH/TO/wp-load.php');
    

    WPDB 的信息和使用方法可以在here 找到。

    【讨论】:

    • 感谢您抽出宝贵时间回答我的问题。我将 alert("success!") 替换为 alert(data),但调用该函数时仍不显示任何警报。为什么?我还想插入数据库查询位于 submit-rating.php(这是位于同一主题文件夹中的另一个 php 文件)。
    • 你能否提供一些很好的资料来了解这一切(尤其是关于 ajax 用于将 javascript 变量传递给另一个 php 文件。)?
    • 您的控制台中是否出现任何错误(chrome 中的 CTRL+SHIFT+I)?我认为问题可能出在网址上,试试/path/to/theme/submit-rating.php。至于消息来源,我相信link 总结得很好。
    • 我在 wordpress.org 中构建它,所以我将 'localhost/mysite/wp-content/themes/zincy-lite/submit-rating.php' 作为 url。这是正确的方式说白了,因为我还没有收到任何警报?
    • 有什么办法可以把链接发给我,让我看看?
    猜你喜欢
    • 2019-04-04
    • 1970-01-01
    • 2017-04-09
    • 2012-10-31
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    相关资源
    最近更新 更多