Wordpress:使用 Ajax 将数据传递到页面 [英] Wordpress: Passing data to a page using Ajax

查看:72
本文介绍了Wordpress:使用 Ajax 将数据传递到页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据从 ajax 调用传递到 Wordpress 的特定页面.
以下是我正在使用的代码:

jQuery.ajax({type: "POST",url: 'single-member-page.php',数据:{大小:'项目'},成功:函数(){//警报(数据);jQuery('#display-member-size').text(data);}});

该脚本不适用于 WP.我还使用控制台检查了页面,但出现错误:

<块引用>

single-member-page.php"未找到

我是 WP 新手,不知道如何将数据从 ajax 调用传递到特定页面.

解决方案

@Daniel

你问了一个很好的问题,在继续解决之前,我们需要了解 wordpress ajax 的拇指规则.

经验法则:

  1. 根据 wordpress 标准,所有 ajax 请求都应该在 javascript 中到达ajaxurl".它实际上包含wp-admin/admin-ajax.php"文件路径.

    示例:

    $.ajax({网址:ajaxurl,数据:{'action':'generateCptApiKey'},成功:功能(数据){控制台日志(数据);},错误:函数(错误抛出){控制台日志(错误抛出);}});

如果您在 wp-admin 仪表板部分 中做一些 sutff 或与 wp-admin 部分相关,例如在 wp-admin 仪表板区域创建选项页面,那么"ajaxurl"全局变量将始终在 javascript 中可用.

如果这个ajax请求是从前端页面/帖子初始化的,那么你必须使用以下方法指定admin-ajax.php文件路径,如果你更好为前端 javascript 本地化它,因此它将在 javascript 变量中可用,就像在 wp-admin 仪表板部分可用一样.

为了实现这一点,我们需要再添加几行代码.

方法:

更新示例代码前端ajax调用:

//注册脚本wp_register_script('ajaxsettings', 'path/to/ajaxsettings.js');//使用新数据本地化脚本$ajaxsettings = 数组('ajaxurl' =>admin_url('admin-ajax.php'));wp_localize_script('ajaxsettings', 'ajaxsettings', $ajaxsettings);//具有本地化数据的入队脚本.wp_enqueue_script('ajaxsettings');$.ajax({网址:ajaxsettings.ajaxurl,数据:{'action':'generateCptApiKey'},成功:功能(数据){控制台日志(数据);},错误:函数(错误抛出){控制台日志(错误抛出);}});

之后我们需要编写方法来处理这个ajax请求并将输出发送回ajax调用.

为了检测 wordpress 中的 ajax 请求调用,它们有两个标准钩子,钩子只是事件,就像我发送 ajax 请求一样,wordpress ajax 相关钩子将触发,我可以在该触发器上调用任何函数.

所以基本上用于处理 ajax 请求的下面有两个钩子:

  1. wp_ajax_(action) :它处理来自已验证/已记录的请求在用户中.(用于后端 wp-admin 仪表板相关任务)
  2. wp_ajax_nopriv_(action) :它处理前端未经身份验证的请求.(用于前端页面/post ajax调用相关任务)

这里的(action) 是您必须在当前主题function.php 文件 中编码的方法的名称,该方法将处理此ajax 请求.

示例:

面向对象的风格:

add_action('wp_ajax_cleanResponseFiles', array($this, 'cleanResponseFiles'));add_action('wp_ajax_nopriv_cleanResponseFiles', array($this, 'cleanResponseFiles'));

注意:这里的cleanResponseFiles"是处理ajax请求的类的方法.并且 $this 指向当前类对象.

程序风格:

add_action('wp_ajax_cleanResponseFiles', 'cleanResponseFiles');add_action('wp_ajax_nopriv_cleanResponseFiles','cleanResponseFiles');

注意:这里的cleanResponseFiles"是在当前主题的function.php文件中添加的函数,它将处理ajax请求.

在这里,我们正在考虑可以从 wp-admin 仪表板或前端页面/帖子发出 ajax 请求.

示例 ajax 请求处理程序方法:

function cleanResponseFiles(){echo "

";打印_r($_POST);echo "</pre>";//在ajax请求处理函数end中总是使用exit()出口();}

经验法则:

  1. 始终在 ajax 请求处理程序方法中使用 exit() 方法,这是必不可少的.
  2. 发送 ajax 请求的最佳做法是使用 Wordpress_nonce.

这只是为了避免CRSF(跨站点请求伪造) 通过添加 Honeypot ,一个带有生成随机密钥和请求的隐藏输入字段处理程序方法,它应该被验证.

这些是我们可用于创建 Wordepress nonce 和验证 Wordpress nonce 和 ajax 请求处理程序或简单 http 请求处理程序的方法.

Wordpress Nonce 方法:

  1. wp_create_nonce :用于创建随机密钥以作为隐藏字段在表单中发送.立>
  2. wp_verify_nonce :用于验证请求处理程序方法中的随机密钥.

我将在此评论中尽快附上 wordpress ajax 调用的工作示例.

I am trying to pass data from an ajax call to a specific page of Wordpress.
Below is the code I am using:

jQuery.ajax({type: "POST",
            url: 'single-member-page.php',
            data:{ size: 'item' }, 
            success: function(){
              //alert(data);
              jQuery('#display-member-size').text(data);
            }
        });

The script does not work for WP. I also inspected the page using the console and I get an error:

single-member-page.php" NOT FOUND

I am new to WP and I do not know how to pass data from an ajax call to a specific page.

解决方案

@Daniel

You asked a very good question, before proceeding to solution we need to understand thumb rules of wordpress ajax.

Thumb Rules:

  1. According to wordpress standards all the ajax request should come to "ajaxurl" in javascript. It actually contains the "wp-admin/admin-ajax.php" file path.

    Example:

    $.ajax({
        url: ajaxurl,
        data: {'action':'generateCptApiKey'},
        success:function(data) {
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });
    

If you are doing some sutff in wp-admin dashboard section or related to wp-admin section like creating an option page in wp-admin dashboard area, than "ajaxurl" global variable will be always available there in javascript.

If case of this ajax request is initialized from front end page/post than you have to specify admin-ajax.php files path using following method and better if you localize this for front-end javascript,So it will be available in javascript variable like it is available in wp-admin dashboard section.

In order to achieve this we need to add few more lines of code.

Method:

Updated Example code front-end ajax call :

// Register the script
wp_register_script( 'ajaxsettings', 'path/to/ajaxsettings.js' );

// Localize the script with new data
$ajaxsettings = array(
    'ajaxurl' => admin_url('admin-ajax.php')
);
wp_localize_script( 'ajaxsettings', 'ajaxsettings', $ajaxsettings );

// Enqueued script with localized data.
wp_enqueue_script( 'ajaxsettings' );

$.ajax({
        url: ajaxsettings.ajaxurl,
        data: {'action':'generateCptApiKey'},
        success:function(data) {
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });

After this we need to write method to handle this ajax request and send output back to the ajax call.

For detecting ajax request call in wordpress they have two standard hooks, hooks are just events like when i send a ajax request, wordpress ajax related hook will trigger and i can call any function on that trigger.

So basically for handling ajax request below are two hooks:

  1. wp_ajax_(action) : It handles request from authenticated / logged in users. (Used for back-end wp-admin dashboard related tasks )
  2. wp_ajax_nopriv_(action) : It handles front-end unauthenticated requests. (Used for front-end page/post ajax call related tasks )

Here (action) is the name of the method that you have to code in your current theme function.php file, and this method will handle this ajax request.

Examples:

Object oriented style:

add_action( 'wp_ajax_cleanResponseFiles', array($this, 'cleanResponseFiles'));
add_action( 'wp_ajax_nopriv_cleanResponseFiles', array($this, 'cleanResponseFiles'));

Note: Here "cleanResponseFiles" is Method of class that will handle ajax request. and $this is pointing current class object.

Procedural style:

add_action( 'wp_ajax_cleanResponseFiles',  'cleanResponseFiles');
add_action( 'wp_ajax_nopriv_cleanResponseFiles','cleanResponseFiles');

Note: Here "cleanResponseFiles" is function added in current theme function.php file and it will handle ajax request.

In this we are considering that ajax request can be made either from wp-admin dashboard or from front-end page/post.

Example ajax request handler method:

function cleanResponseFiles(){
    echo "<pre>";
    print_r($_POST);
    echo "</pre>";

    //Always use exit() in ajax request handler function end
    exit();
}

Thumb Rule :

  1. Always use exit() method in ajax request handler method, it's essential.
  2. The best practice of sending ajax request is use Wordpress_nonce.

It's just for avoding CRSF (Cross site request forgery ) by adding Honeypot , A hidden input field with generated random key and at in request handler method it should be validated.

These are the methods that we can use for creating Wordepress nonce and verifying Wordpress nonce and ajax request handler or simple http request handler.

Wordpress Nonce Methods:

  1. wp_create_nonce : Used for creating random key for sending in forms as a hidden field.
  2. wp_verify_nonce : Used for verifying random key in request handler method.

I will attach a working example of wordpress ajax call ASAP in this comment.

这篇关于Wordpress:使用 Ajax 将数据传递到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆