GVKun编程网logo

WordPress中利用AJAX技术进行评论提交的实现示例(wordpress ajax)

14

对于WordPress中利用AJAX技术进行评论提交的实现示例感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍wordpressajax,并为您提供关于javascript–WordPress使

对于WordPress中利用AJAX技术进行评论提交的实现示例感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍wordpress ajax,并为您提供关于javascript – WordPress使用WordPress将ajax值传递给特定页面、php – 在WordPress中使用Ajax发送邮件、php – 在wordpress中创建ajax调用.我需要包括什么才能访问wordpress功能、php – 在WordPress插件中使用AJAX的有用信息。

本文目录一览:

WordPress中利用AJAX技术进行评论提交的实现示例(wordpress ajax)

WordPress中利用AJAX技术进行评论提交的实现示例(wordpress ajax)

一直对 wordpress 的 Ajax 交互研究感兴趣,也一直很关注于这方面的技术,谈到 wordpress Ajax 就不得不谈到评论 Ajax提交,作为一个博客、论坛评论的 Ajax 提交不仅可以改善用户体验,还可以大幅缩减服务器开支,毕竟输出单条评论内容比重新组织输出一个页面要简单的多。 虽说现在访问量一直比较低,不存在服务器压力的问题,但一向注重用户体验的我,当然不能放弃这么一个提升用户体验的机会。今天抽了一下午的空,把这个主题的 Ajax 评论提交初步完成了。

直接开门见山,直接上代码:(原理及思路在最后) 根据自己主题不同结构,以下代码请自行调整。

wordpress Ajax 提交评论 PHP 代码

在主题 function.PHP 文件中加入如下部分。

dbh) { echo('Our database has issues. Try again later.'); die(); } nocache_headers(); $comment_post_ID = (int) $_POST['comment_post_ID']; $status = $wpdb->get_row("SELECT post_status,comment_status FROM $wpdb->posts WHERE ID = '$comment_post_ID'"); if ( empty($status->comment_status) ) { //这一套判断貌似抄的 wp 源代码 。详见:include/comment.PHP do_action('comment_id_not_found',$comment_post_ID); fail('The post you are trying to comment on does not currently exist in the database.'); } elseif ( 'closed' == $status->comment_status ) { do_action('comment_closed',$comment_post_ID);; fail('Sorry,comments are closed for this item.'); } elseif ( in_array($status->post_status,array('draft','pending') ) ) { do_action('comment_on_draft',$comment_post_ID); fail('The post you are trying to comment on has not been published.'); } $comment_author = trim(strip_tags($_POST['author'])); $comment_author_email = trim($_POST['email']); $comment_author_url = trim($_POST['url']); $comment_content = trim($_POST['comment']); // If the user is logged in $user = wp_get_current_user(); if ( $user->ID ) { $comment_author = $wpdb->escape($user->display_name); $comment_author_email = $wpdb->escape($user->user_email); $comment_author_url = $wpdb->escape($user->user_url); if ( current_user_can('unfiltered_html') ) { if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) { kses_remove_filters(); // start with a clean slate kses_init_filters(); // set up the filters } } } else { if ( get_option('comment_registration') ) fail('火星人?注册个?'); } $comment_type = ''; if ( get_option('require_name_email') && !$user->ID ) { if ( 6> strlen($comment_author_email) || '' == $comment_author ) fail('Oopps,名字[Name]或邮箱[email]不对。'); elseif ( !is_email($comment_author_email)) fail('Oopps,邮箱地址[Email]不对。'); } if ( '' == $comment_content ) fail('是不是应该写点什么再提交?'); // Simple duplicate check $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' "; if ( $comment_author_email ) $dupe .= "OR comment_author_email = '$comment_author_email' "; $dupe .= ") AND comment_content = '$comment_content' LIMIT 1"; if ( $wpdb->get_var($dupe) ) { fail('评论重复了!有木有!'); } $commentdata = compact('comment_post_ID','comment_author','comment_author_email','comment_author_url','comment_content','comment_type','user_ID'); if( !$user->ID ){ $result_set = $wpdb->get_results("SELECT display_name,user_email FROM $wpdb->users WHERE display_name = '" . $comment_author . "' OR user_email = '" . $comment_author_email . "'"); if ($result_set) { if ($result_set[0]->display_name == $comment_author){ fail('博主你也敢冒充?'); } else { fail('博主你也敢冒充?'); } } } $comment_id = wp_new_comment( $commentdata ); $comment = get_comment($comment_id);

if( !$user->ID ){
setcookie('commentauthor' . COOKIEHASH,$comment->comment_author,time() + 30000000,COOKIEPATH,COOKIE_DOMAIN);
setcookie('comment_authoremail' . COOKIEHASH,$comment->comment_author_email,COOKIE_DOMAIN);
setcookie('comment_authorurl' . COOKIEHASH,clean_url($comment->comment_author_url),COOKIE_DOMAIN);
}
@header('Content-type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
xz_comment($comment,null);//这是我的调用评论函数,换成你的函数名。
die();
}
}
add_action('init','ajax_comment');

Javascript 中代码

注意:以下代码需要 Jquery 框架支援。 javascript onload 代码中加入以下部分。

rush:js;"> if (jQuery('#commentform').length) { jQuery('#commentform').submit(function(){ // 截获提交动作 //ID为 commentform 的表单提交时发生的函数,也就是整个留言输入框 form 的ID。 var ajaxCommentsURL = window.location.href; jQuery.ajax({ url: ajaxCommentsURL,data: jQuery('#commentform').serialize()+'&action=ajax_comment',type: 'POST',beforeSend: function() { jQuery('#commenterror').hide(); jQuery('#commentload').fadeIn(); },error: function(request) { //发生错误时 jQuery('#commenterror').html(request.responseText); jQuery('#commentload').hide(); //隐藏 submit jQuery('#commenterror').fadeIn(); //显示 error },success: function(data) { jQuery('textarea').each(function(){ this.value=''; }); jQuery('#commenterror').fadeOut(); if(jQuery(".commentlist li.comment").first().length != 0){jQuery(".commentlist li.comment").first().before(data)} else {jQuery("ol.commentlist").append(data)} jQuery(".commentlist li.comment").first().hide(0,function(){$(this).slideDown(1000)}); jQuery('#cmt-submit').attr('disabled',true).css({"background-color":"#6C6C6C","color":"#E0E0E0"}); jQuery('#commentload').fadeOut(1600); setTimeout(function() { jQuery('#cmt-submit').removeAttr('disabled').css({"background-color":"#0086C5","color":"#FFFFFF"}); },3000); } }); return false; } ); }

注:代码仍有改进需求,因为没有时间,所以就没有再进化。

CSS 代码

css 随意部分添加。

rush:css;"> #commentload,#commenterror{ display: none; margin: 5px 0 0 0; color:#D29A04; float: left; font-size:16px; padding:0 0 0 20px; } #commentload{ background: url("img/loading.gif") no-repeat bottom left ; } #commenterror{ background: url("img/error.png") no-repeat bottom left ; }

原理、思路

原理: Javascript 提交数据 PHP响应并输出结果 Javascript 得到结果并显示 思路: 点击提交按钮后,Javascript 截获提交动作 截获提交的各项数据(Name、Email、Web、Comment-text) 利用 Javascript Jquery 模拟浏览器提交POST(Name、Email、Web、Comment-text)请求之wordpress Function.PHP 文件中构造一个接受请求的函数,即本列中ajax_comment函数 如果请求无错误,输出正确结果 如果请求有错误,输出错误结果 Javascript 获得正确结果,动态添加到评论列表中 Javascript 获得错误结果,动态添加到提交提示栏

改进

样式方面,我确实没什么美感,所以正在学习中。 提交按钮在点击至获得返回结果后3秒的时间里应该都是变灰失效状态,这一点之前因为在本机测试,提交瞬间完成没有注意到,远程测试的时候发现了,但要改的话还要进行测试,时间太紧就不改了,有机会再改进一下。

总结

因为 wordpress 主题中评论样式的自由性、多样性,所以貌似至今一直没有一款通用性的AJAX 评论插件, 一些高手也只能在优化自己博客之余,把思路和部分通用核心代码做一下公布, 所以想要实现一些炫酷的功能要不有高人帮你, 要不你就只能好好学代码,期待有一日能够厚积薄发了。 效果请自行提交评论验证。

javascript – WordPress使用WordPress将ajax值传递给特定页面

javascript – WordPress使用WordPress将ajax值传递给特定页面

我想将变量传递给特定页面.我找到了一个简单的例子,解释了如何在wordpress中使用ajax.

JavaScript的:

jQuery(document).ready(function($) {

// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';

// This does the ajax request
$.ajax({
    url: ajaxurl,
    data: {
        'action':'example_ajax_request',
        'fruit' : fruit
    },
    success:function(data) {
        // This outputs the result of the ajax request
        console.log(data);
    },
    error: function(errorThrown){
        console.log(errorThrown);
    }
});  

});

要在functions.PHP中插入的PHP片段

function example_ajax_request() {

// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {

    $fruit = $_REQUEST['fruit'];

    // Let's take the data that was sent and do something with it
    if ( $fruit == 'Banana' ) {
        $fruit = 'Apple';
    }

    // Now we'll return it to the javascript function
    // Anything outputted will be returned in the response
    echo $fruit;

    // If you're debugging, it might be useful to see what was sent in the $_REQUEST
    // print_r($_REQUEST);

}

// Always die in functions echoing ajax content
  die();
 }

add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );


   wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' =>   admin_url( 'admin-ajax.PHP' ) ) );

不幸的是我无法传递变量.我检查了代码,我收到了这个错误:

Error: ajax_object is not defined

您是否知道另一种获得相同结果的方法?

解决方法:

你很近,但有一些小事丢失了……

我在评论中的意思是,你需要在两者中使用’ajax-script’这样使用它:

add_action('wp_enqueue_scripts', 'add_js_scripts'); 
add_js_scripts(){
    wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
    wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' =>   admin_url( 'admin-ajax.PHP' ) ) );
}

将$_REQUEST更改为$_POST:

function example_ajax_request() {

    // The $_REQUEST contains all the data sent via ajax
    if ( isset($_POST) ) {

        $fruit = $_POST['fruit'];

        // Let's take the data that was sent and do something with it
        if ( $fruit == 'Banana' ) {
            $fruit = 'Apple';
        }

        // Now we'll return it to the javascript function
        // Anything outputted will be returned in the response
        echo $fruit;

        // If you're debugging, it might be useful to see what was sent in the $_POST
        // print_r($_POST);

    }

    // Always die in functions echoing ajax content
      die();

 }

添加了add_action(‘wp_ajax_nopriv_ …):

add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' ); // <= this one
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );

对于你的jQuery脚本script.js文件,有两件重要的遗漏:

jQuery(document).ready(function($) {

    /* We'll pass this variable to the PHP function example_ajax_request */
    var fruit = 'Banana';

    /* This does the ajax request */
    $.ajax({
        url: ajax_object.ajaxurl, /* <====== missing here */
        type : 'post', /*    <========== and missing here */
        data: {
            'action':'example_ajax_request',
            'fruit' : fruit
        },
        success:function(data) {
            /* This outputs the result of the ajax request */
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });  

});

这应该现在工作……

参考文献:

> Using AJAX With PHP on Your WordPress Site Without a Plugin
> How to use Ajax with your WordPress Plugin or Theme?

php – 在WordPress中使用Ajax发送邮件

php – 在WordPress中使用Ajax发送邮件

我正在尝试使用Ajax通过我创建的Web表单发送电子邮件,但我迷路了.我不知道Ajax如何在wordpress中运行.

我首先创建了一个动作

add_action( 'wp_ajax_siteWideMessage','wpse_sendmail' );

应该检索数据并发送邮件的功能是:

function wpse_sendmail()
{
    $for = like_escape($_POST['forwhat']);
    $email = like_escape($_POST['email']);
    $headers = 'From: '.$email ."\r\n".'Reply-To: '.$email;
    $message = like_escape($_POST['message_message']);
    $respond = like_escape($_POST['message_email']);

    wp_mail( "support@ontrgt.net","(OTN) Support: ".$support,$message,$headers); 
}

最后,js是这样的:

$("#contact-send").click(function(){
    var forwhat = $("#contact-for").val();
    var name = $("#contact-name").val();
    var email = $("#contact-email").val();

    $.post( "<?PHP echo esc_js( site_url() ) ?>",{ siteWideMessage:"null",forwhat: forwhat,name: name,email:email },function(){
            console.log("success");
    });
});

我不太清楚我在这里缺少什么.有人可以帮我理解wordpress的Ajax流程吗?

UPDATE

到目前为止,我更新了我的代码:

PHP

add_action( 'wp_ajax_siteWideMessage','wpse_sendmail' );
add_action( 'wp_ajax_nopriv_siteWideMessage','wpse_sendmail' );

function wpse_sendmail()
{
    $for = $_POST['forwhat'];
    $email = $_POST['email'];
    $headers = 'From: '.$email ."\r\n".'Reply-To: '.$email;
    $message = $_POST['message_message'];
    $respond = $_POST['message_email'];

    /*if(wp_mail( "support@ontrgt.net","(OTN) Support: ".$for,$headers))
    {
        echo "WOOHOO";
    }*/

    if($for)
    {
        //Just to see if there is any response.
        echo "Whoohoo";
    }

    die();
}

JS

$("#contact-send").click(function(){
    var forwhat = $("#contact-for").val();
    var name = $("#contact-name").val();
    var email = $("#contact-email").val();

    var data = { action:'siteWideMessage',forwhat:forwhat,name:name,email:email };
    $.post('<?PHP echo admin_url("admin-ajax.PHP"); ?>',data,function(response) {
        alert(response);
    });
});

wordpress仍然没有响应我的AJAX命令.我正在使用inspect元素,我看不到任何数据被传递.

首先,您需要添加两个操作,一个用于明确要求使其工作的非登录用户,例如类似这样的操作(基本上在您的functions.PHP文件中):
add_action( 'wp_ajax_siteWideMessage','wpse_sendmail' );

然后,你需要向admin-ajax.PHP发出请求,所以在jQuery函数中,你可以使用这样的东西:

$("#contact-send").click(function(e){

    e.preventDefault(); // if the clicked element is a link

    //...

    var data = { 'action':'siteWideMessage','more':'values' };

    $.post('<?PHP echo admin_url('admin-ajax.PHP'); ?>',function(response) {
        console.log(response);
    });

});

确保将exit / die放在服务器端处理程序的末尾,例如:

function wpse_sendmail()
{
    // Process the post data...

    if(mail(...)) {
        echo 'success';
    }
    else {
        echo 'Failed';
    }

    die();
}

在您的成功回调中,响应变量将获得从服务器端发送的响应,即成功/失败.有更好的方法来执行此操作(使用wp_localize_script等).阅读this detailed article.此外,如果你想返回一个json响应,那么你可以使用$.json(‘url’,func).

如果您感到困惑,那么让我告诉您,您应该向admin-ajax.PHP发出请求并通过请求传递操作,在这种情况下它是siteWideMessage,因此wordpress将调用使用add_action hook注册的处理程序你的情况是wpse_sendmail.Eid穆巴拉克:-)

php – 在wordpress中创建ajax调用.我需要包括什么才能访问wordpress功能

php – 在wordpress中创建ajax调用.我需要包括什么才能访问wordpress功能

我在wordpress中执行jquery ajax请求.这称为内部PHP脚本.
这个PHP脚本需要能够访问某些wordpress功能,如… functions.PHP
这对我来说很简单.
我无法做的是访问当前wordpress用户,$wpdb对象的信息.
我的问题是…是否有一些wordpress文件,我可以包含,这使我可以访问所有数据(和functions.PHP).
我希望你能理解我正在访问的东西,因为我知道这可能是世界上最彻底的解释
:d

解决方法:

糟糕的方式(正如其他人所指出的那样)

当我创建一些与wordpress一起使用的自定义PHP时,我包含了wp-load.PHP文件.然后加载所需的一切,包括$wpdb.

require_once('wp-load.PHP'); // relative path from your PHP file

global $wpdb;
$wpdb->show_errors = TRUE; // useful for when you first start

我发现这是一个很好的起点,可以快速修复.但是你必须记住,这将加载比你实际需要的功能更多的功能.因此导致性能时间变慢.

好方法

一旦功能变得更加复杂,“糟糕”的实施并不是那么好.所以我转而编写插件. wordpress codex包含有关使用AJAX和插件的良好信息:http://codex.wordpress.org/AJAX_in_Plugins

在最基本的形式中,您需要注册您的AJAX钩子:

// 'wp_ajax_foo' is the hook, 'foo' is the function that handles the request
add_action( 'wp_ajax_foo', 'foo');

您还需要相应的功能(在本例中为foo):

function foo() {
    // handle the AJAX request
    $bar = $_POST['bar'];
}

然后在JavaScript中,您可以识别要与action属性一起使用的钩子,但忽略wp_ajax部分:

$.post(ajaxurl, { action: 'foo', bar: true }, function(response) {
    // do something with response
});

php – 在WordPress插件中使用AJAX

php – 在WordPress插件中使用AJAX

我正在尝试创建一个基于 AJAX的wordpress示例插件.我阅读了一个教程并做了一个插件,但它没有用.我是AJAX的新手.这是我试过的代码:
<?PHP
class ajaxtest {

    function ajaxcontact() {
        ?>
        <div id="Feedback"></div>
        <form name="myform" id="myform">
            <li>
                <label for fname>First Name</label><input type="text" id="fname" name="fname" value=""/>
            </li>
            <li>
                <label for lname>Last Name</label><input type="text" id="lname" name="lname" value=""/>
            </li>
            <input type="submit" value="Submit" id="submit" name="submit"/>
        </form>
        <script type="text/javascript">
            jQuery('#submit').submit(ajaxSubmit);

            function ajaxSubmit() {

                var newcontact = jQuery(this).serialize();

                jQuery.ajax({
                    type: "POST",url: "/wp-admin/admin-ajax.PHP",data: newcontact,success: function(data) {
                        jQuery("#Feedback").html(data);
                    }
                });

                return false;
            }
        </script>
        <?PHP
    }

    function addcontact() {
        $fname = $_POST['fname'];
        if ($fname != "") {
            echo "Your Data is" . $fname;
        } else {
            echo "Data you Entered is wrong";
        }

        die();
    }

}

function jquery_add_to_contact() {
    wp_enqueue_script('jquery');  // Enqueue jQuery that's already built into wordpress
}

add_action('wp_enqueue_scripts','jquery_add_to_contact');
add_action('wp_ajax_addcontact',array('ajaxtest','addcontact'));
add_action('wp_ajax_nopriv_addcontact','addcontact')); // not really needed
add_shortcode('cform','ajaxcontact'));

我用它作为短代码,但我没有得到输出.怎么了?

wordpress环境

首先,为了完成这项任务,建议注册然后将jQuery脚本排入队列,将脚本推送到服务器.这些操作将挂钩在wp_enqueue_scripts动作钩子中.在同一个钩子中,你应该把它用于包含任意JavaScript的wp_localize_script.通过这种方式,前端将有一个JS对象.该对象进行jQuery句柄使用的正确url.

请看看:

> wp_register_script();功能
> wp_enqueue_scripts勾
> wp_enqueue_script();功能
> wp_localize_script();功能

在主插件文件中,添加这些.

add_action( 'wp_enqueue_scripts','so_enqueue_scripts' );
function so_enqueue_scripts(){
  wp_register_script( 'ajaxHandle',plugins_url('PATH TO YOUR SCRIPT FILE/jquery.ajax.js',__FILE__),array(),false,true );
  wp_enqueue_script( 'ajaxHandle' );
  wp_localize_script( 'ajaxHandle','ajax_object',array( 'ajaxurl' => admin_url( 'admin-ajax.PHP' ) ) );
}

文件:jquery.ajax.js

这个文件进行AJAX调用.

jQuery(document).ready( function($){
  //Some event will trigger the ajax call,you can push whatever data to the server,simply passing it to the "data" object in ajax call
  $.ajax({
    url: ajax_object.ajaxurl,// this is the object instantiated in wp_localize_script function
    type: 'POST',data:{ 
      action: 'myaction',// this is the function in your functions.PHP that will be triggered
      name: 'John',age: '38'
    },success: function( data ){
      //Do something with the result from server
      console.log( data );
    }
  });
});

还要在插件主文件中添加以下代码.

最后,在你的functions.PHP文件中,应该有你的AJAX调用触发的函数.
记住后缀:

> wp_ajax(仅限注册用户或管理面板操作的功能)
> wp_ajax_nopriv(允许无特权用户的功能)

这些后缀加上操作组成了您的操作名称:

wp_ajax_myaction或wp_ajax_nopriv_myaction

add_action( "wp_ajax_myaction","so_wp_ajax_function" );
add_action( "wp_ajax_nopriv_myaction","so_wp_ajax_function" );
function so_wp_ajax_function(){
  //DO whatever you want with data posted
  //To send back a response you have to echo the result!
  echo $_POST['name'];
  echo $_POST['age'];
  wp_die(); // ajax call must die to avoid trailing 0 in your response
}

今天关于WordPress中利用AJAX技术进行评论提交的实现示例wordpress ajax的介绍到此结束,谢谢您的阅读,有关javascript – WordPress使用WordPress将ajax值传递给特定页面、php – 在WordPress中使用Ajax发送邮件、php – 在wordpress中创建ajax调用.我需要包括什么才能访问wordpress功能、php – 在WordPress插件中使用AJAX等更多相关知识的信息可以在本站进行查询。

本文标签:

上一篇利用CSS、JavaScript及Ajax实现高效的图片预加载(js前端图片预加载)

下一篇WordPress中利用AJAX异步获取评论用户头像的方法(wordpress ajax)