在Wordpress中使用Ajax将某些文本输出到DIV中


Output certain text into DIV using Ajax in Wordpress

我是Ajax的新手。通过大量的错误尝试,我有了一个基本的例子,我正在寻求扩展它

我正在开发一个带有美国图像地图的自定义Wordpress页面,我需要使用Ajax在div中填充每个州的信息。

当用户点击定义为纽约的地图区域时,会触发一个href,如下所示:href="javascript:getStateInfo('newyork')"

这是我的JS函数:

function getStateInfo(name)
    {
        var name = this.name;
        jQuery.ajax({
        type: 'POST',
        url: '/wp-admin/admin-ajax.php',
    data: {
        action: name, // the PHP function to run
    },
    success: function(data, textStatus, XMLHttpRequest) {
        jQuery('#infoDiv').html(''); // empty an element
        jQuery('#infoDiv').append(data); // put our list of links into it
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        if(typeof console === "undefined") {
            console = {
                log: function() { },
                debug: function() { },
            };
        }
        if (XMLHttpRequest.status == 404) {
            console.log('Element not found.');
        } else {
            console.log('Error: ' + errorThrown);
        }
    }
});}

我想用ajax获取信息,所以在我的functions.php文件中我有

function newyork()
{
    echo 'this is info on new york state';
    die();
}
add_action( 'wp_ajax_nopriv_newyork', 'newyork' );
add_action( 'wp_ajax_newyork', 'newyork' );

显然,这段代码不起作用,我甚至不确定是否应该为每个状态编写50个不同的函数,并使用add_action。如果有人知道实现这一点的更好方法,我真的很想学习如何最有效地实现这一目标?

这实际上非常简单,甚至根本不需要使用aJax。

然而,你定义了地图的区域,你的js可以看起来像这个

$('.state').on('click', function(){
    var state = $(this).val();
    $('#display').append(state);
});

您也可以在$('#display').empty();中添加,以在添加新数据之前清除#display元素内的当前数据。

以下是您可以编辑的代码,以加载到页面中,其中包含您想要的文本

$('.state').on('click', function(){
    var state = $(this).val();
    $.ajax({
        type: "POST",
        url: 'goes here',
        data: {state : state},
        success: function(displayState){
            $('#display').html(displayState);
        }
    )};
});

然后,您加载的页面可以被写入以显示信息,具体取决于您单击的状态。