在WordPress插件中使用AJAX [英] Using AJAX in a WordPress plugin

查看:110
本文介绍了在WordPress插件中使用AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个基于AJAX的WordPress示例插件.我读了一个教程并做了一个插件,但是没有用.我是AJAX的新手.这是我尝试的代码:

I'm trying to create a WordPress sample plugin based in AJAX. I read a tutorial and did a plugin, but it's not working. I am new to AJAX. Here is the code I tried:

<?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', array('ajaxtest', 'addcontact')); // not really needed
add_shortcode('cform', array('ajaxtest', 'ajaxcontact'));

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

I used this as a shortcode, but I didn't get an output. What's the mistake?

推荐答案

WordPress环境

首先,为了完成此任务,建议先注册然后加入一个jQuery脚本,该脚本会将请求推送到服务器.这些操作将被钩在wp_enqueue_scripts动作钩子中.在同一个钩子中,应放置wp_localize_script,它用于包含任意JavaScript.通过这种方式,前端将提供一个JS对象.该对象进行正确的URL,以供jQuery句柄使用.

First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. These operations will be hooked in wp_enqueue_scripts action hook. In the same hook you should put wp_localize_script that it's used to include arbitrary JavaScript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle.

请看一下:

  1. wp_register_script(); 函数
  2. wp_enqueue_scripts 钩子
  3. wp_enqueue_script(); 函数
  4. wp_localize_script(); 函数
  1. wp_register_script(); function
  2. wp_enqueue_scripts hook
  3. wp_enqueue_script(); function
  4. wp_localize_script(); function

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

In main plugin file, add these.

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调用.

This file makes the AJAX call.

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 );
    }
  });
});

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

Also add below codes to plugin main file.

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

Finally, on your functions.php file, there should be the function triggered by your AJAX call. Remember the suffixes:

  1. wp_ajax(仅允许已注册用户或管理面板操作使用此功能)
  2. wp_ajax_nopriv(允许无特权用户使用该功能)
  1. wp_ajax ( allow the function only for registered users or admin panel operations )
  2. wp_ajax_nopriv ( allow the function for no privilege users )

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

These suffixes plus the action compose the name of your action:

wp_ajax_myactionwp_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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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