【问题标题】:How to receive data from database via jquery? [wordpress .js]如何通过jquery从数据库接收数据? [wordpress.js]
【发布时间】:2015-01-19 10:25:48
【问题描述】:

我正在尝试从我的 .js WordPress 主题文件中的数据库中获取少量数据。 我尝试使用 jquery 的 .post() ,但没有任何反应。

还请给我建议任何替代方案。

.js 文件中的代码

jq.post("../abc.php",
        {
        name:"kumar",
        accId:window.accommodationId

        },  function(data,status)
            {
                alert("hello");

             //alert("Data: " + data + "\nStatus: " + status);
            }
        );

abc.php 文件中的代码

<?php
global $wpdb;

$max_minAge = $wpdb->get_results( "SELECT price_per_day FROM  wp_byt_accommodation_vacancies where accommodation_id='1741'" );   

echo $max_minAge[0]->price_per_day;
?>

【问题讨论】:

标签: php jquery wordpress


【解决方案1】:

你可以在你的functions.php文件中使用这样的wp_ajax钩子

  // script atyle add at frontend
    add_action( 'wp_enqueue_scripts','my_scripts_style');

 function my_scripts_style()
{
    wp_enqueue_script( 'scriptid', PATH_TO . 'script.js', array('jquery') );
    // localize the script
    wp_localize_script( 'scriptid', 'myAjax', array( 'url' =>admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce( "ajax_call_nonce" )));
}

然后添加ajax钩子

   // action for execute ajax from frontend 
    add_action( 'wp_ajax_nopriv_execute_ajax','execute_ajax');

function execute_ajax() 
{
    $nonce = check_ajax_referer( 'ajax_call_nonce', 'nonce' );
    if($nonce==true)
    {
    // here you will perform all the db communication get data from db and send it to the view area.
    echo 'test this';   
    die();
     }
}

然后在您通过上面的enque_script 包含的 js 文件中。用这个

jQuery(function(){
jQuery('.click-onthis').live('click', function(){ // get data by click
    var data = {
                    action: 'execute_ajax',
                    nonce: myAjax.nonce,
                    // anyother code etc
                };

                jQuery.post( myAjax.url, data, function(response) 
                {
                    if(response=='success')
                    {

                    }
                });
        });
    });

jquery click-on-this 将在单击链接时起作用,您可以在加载或任何其他事件时进行协作

【讨论】:

  • 如果我想加载它怎么办,这意味着当这个 js 加载时应该回显值。
  • 只去掉点击功能
  • 很难实现你的建议,好吧,让我们筛选一下,我应该在我的 .php 文件中添加前两个部分,然后在 PATH_TO 上写什么,以及在哪里添加查询。
  • 我不知道其他答案在说什么,我只是通过 Wordpress 方式添加的东西。并且php函数和钩子将被添加到您的functions.php文件中,jquery脚本将在您的脚本文件中,您在functions.php中加入PATH_TO,您只需添加jquery文件的路径,如果它在 wordpress 主题的 js 目录中,那么它将是 get_bloginfo('template_url').'/js/script.js'
【解决方案2】:

您可以使用jQuery AJAX get 速记:

$.get( "../abc.php", function( data ) {
  alert( "Data Loaded: " + data );
});

温馨提示:由于您是从文件中获取数据,您应该使用GET

【讨论】:

  • 没有出现警告,如何检查 $wpdb 是否正常工作。我已将此文件放在主题的根文件夹中
  • 在这个 JS 之前你是否包含了 jQuery?
  • 当然,但这是我正在关注的 wordpress 主题.. 我是新人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多