jquery - wordpress插件中的ajax错误

标签 jquery ajax wordpress plugins

我正在为 WordPress 编写一个插件。该插件有一个小部件,其中包含按钮和文本框。 按钮有 onclick 事件。 当该事件发生时,我需要使用 ajax 将文本框数据发布到 php 文件 ajax代码不会返回错误,但php无法获取数据。

这是我的 JS 文件

 function F()
    {
        var x=document.getElementById('last').value;


        jQuery.ajax({
            type: "POST",
            url: 'http://localhost/wordpress/wp-content/plugins/Hovo/Scripts/vote.php',         
            data: x,
            success: function() {
                alert('Sends successfully');
            },
            error: function(jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
            }
        });
    }

这是我的 php 文件

<?php
    if(isset($_POST["anun"]))
    {
        echo $_POST['anun'];
    }
    else
    {
        echo "error";
    }
?>

请帮忙解决这个问题

最佳答案

在您的 PHP $_POST 中,需要一个键/值对,而您在 ajax 中仅发送一个值。其中“anun”是键,x 中存储的内容是值。

由于您没有将 key “anun”发送到 $_POST,因此它无法返回存储在 x 中的值,因为您的 if 条件失败。

您应该能够通过稍微更改 ajax 调用来纠正此问题:

function F() {

    var x = document.getElementById('last').value;

    jQuery.ajax({
        type: "POST",
        url: 'http://localhost/wordpress/wp-content/plugins/Hovo/Scripts/vote.php',         
        data: { anun: x },
        success: function() {
            alert('Sends successfully');
        },
        error: function(jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
        }
    });
}

为了确保您获得正确的 x 值,请尝试在 ajax 调用之前使用 console.log(x); 并检查浏览器控制台以查看它返回什么。

如果它没有返回正确的值或根本不返回任何内容,请尝试更改:

var x = document.getElementById('last').value;

简单地说:

x = jQuery('#last').val();

关于jquery - wordpress插件中的ajax错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29803786/

相关文章:

javascript - 提取json数据

javascript - 访问对象的嵌套属性

php - 如何渲染ajax返回的文件

PHP & MySql 和 Ajax 自动建议问题

css - 设置默认 WordPress 搜索框的样式

javascript - 加载 css 文件时出现问题

javascript - 当 SweetAlert 出现在屏幕上时停止控件

ajax - firebug 网络监视器选项

wordpress - WooCommerce 预定操作选项卡

php - 在 Woocommerce 中检索产品分类的 SQL 查询