php 在 WordPress 插件中使用 AJAX

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17855846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:34:43  来源:igfitidea点击:

Using AJAX in a WordPress plugin

phpjquerywordpress

提问by Vignesh Pichamani

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:

我正在尝试创建一个基于 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', 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?

我将此用作短代码,但没有得到输出。有什么错误?

回答by rams0610

WordPress environment

WordPress环境

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_scriptsaction hook. In the same hook you should put wp_localize_scriptthat 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.

首先,为了完成这个任务,建议注册然后入队一个 jQuery 脚本,它将请求推送到服务器。这些操作将被钩在wp_enqueue_scripts动作钩子中。在同一个钩子中,您应该wp_localize_script指出它用于包含任意 JavaScript。通过这种方式,前端就有一个可用的 JS 对象。该对象携带 jQuery 句柄使用的正确 url。

Please take a look to:

请看一看:

  1. wp_register_script();function
  2. wp_enqueue_scriptshook
  3. wp_enqueue_script();function
  4. wp_localize_script();function
  1. wp_register_script(); 功能
  2. wp_enqueue_scripts钩子
  3. wp_enqueue_script(); 功能
  4. wp_localize_script(); 功能

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

File: jquery.ajax.js

文件:jquery.ajax.js

This file makes the AJAX call.

该文件进行 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 );
    }
  });
});

Also add below codes to plugin main file.

还将以下代码添加到插件主文件中。

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

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

  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 )
  1. wp_ajax(仅允许注册用户或管理面板操作的功能)
  2. wp_ajax_nopriv(允许无权限用户的功能)

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

这些后缀加上动作构成了你的动作的名称:

wp_ajax_myactionor wp_ajax_nopriv_myaction

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
}

回答by Mark

You need to add an 'action' to your AJAX call.

您需要在 AJAX 调用中添加一个“操作”。

jQuery.ajax({
  type: "POST",
  url: "/wp-admin/admin-ajax.php",
  data: newcontact,
  action: 'addcontact',
  success: function(data) {
    jQuery("#feedback").html(data);
  }
});

The value should be the same as the add_action hook to wp_ajax. e.g.

该值应与 wp_ajax 的 add_action 挂钩相同。例如

add_action( wp_action_{action_value}, 'myfunc' );

This allows WordPress to know which function to run when the AJAX call is made.

这允许 WordPress 在进行 AJAX 调用时知道要运行哪个函数。

This Codex page has some useful infoand this article describeshow to better refine the code you have.

这个 Codex 页面有一些有用的信息这篇文章描述了如何更好地优化你拥有的代码。