简体   繁体   English

在wordpress插件页面中调用Jquery Ajax无法正常工作

[英]Jquery Ajax call in wordpress plugin page not working

In wordpress I created a plugin which has the following files 在wordpress中,我创建了一个包含以下文件的插件

Statistics visitor 统计访客

<?php
/*
Plugin Name: Wp Visitor Statistics
Plugin URI: 
Description: Statistics about Visitors
Author: 
Version: 1.0.1
Author URI:
*/

ob_start();
define('STATISTICS_FOLDER', dirname(plugin_basename(__FILE__)));

//CREATING MENU PAGES IN SIDEBAR
add_action('admin_menu','statistics_admin_menu');

    function statistics_admin_menu() { 
        $icon_url=get_option('siteurl').'/wp-content/plugins/'.STATISTICS_FOLDER."/lea.png";
        add_menu_page("Statistics","Statistics",10,__FILE__,"Settings",$icon_url); 
        add_submenu_page(__FILE__,"Stat Report","Statistics Report",10,"visitor_stat/statreport.php");      
    } 

function Settings()
{

    $plugindir = get_option('siteurl').'/wp-content/plugins/'.STATISTICS_FOLDER.'/';
    echo "<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'/></script>\n";
    echo "<br/>";
    echo "<script type='text/javascript' src='$plugindir/calendar/myfuncvisit.js'/></script>\n";
    echo "<br/>";
    echo "<script type='text/javascript' src='$plugindir/calendar/jquery.datepick.js'/></script>\n";
    echo "<br/>";
    echo "<link rel='stylesheet' href='$plugindir/calendar/jquery.datepick.css' type='text/css' />\n";  
    echo "<br/>";
echo "<script type='text/javascript'>
$(function() {
    $('#popupDatepicker').datepick({dateFormat: 'yyyy-mm-dd'});
});
</script>";
echo "<br/>";

echo "<div class='wrap'>
<form action='' name='frm1'>
<strong>Todays Visit : <span id='todays_visit'> </span> | Overall Visit :<span id='overall_visit'></span> ( Original Data )<br /></strong><br />
Todays Visit plus : <input type='text' name='todays_visit_plus' id='todays_visit_plus' value=''/><br /><br />
Overall Visit plus : <input type='text' name='overall_visit_plus'  id='overall_visit_plus' value=''/><br /><br />
Overall Visit Start Date : <input type='text' class='overall_visit_startdate' id='popupDatepicker'><br /><br />
<div id='msg_save'></div>
<input type='button' name='save' id='save' value='save'/>
</form>
</div>";

}
?>  

Then it call the another file js 然后它调用另一个文件js

myfuncvisit.js myfuncvisit.js

// JavaScript Document
            $(document).ready(function(){

                // loading image displaying function
                function loading_show(divid){

                   $('#'+divid).html("<div class='item' style='padding:45% 0;text-align:center;font-size:11px;color:#666666;'><center><img width='16' height='16' src='loading.gif'><br>Loading</center></div>").fadeIn('swing');
                }

                // function to show the feed list 
                function loadData(){   
                    $.ajax
                    ({
                        type: "POST",
                        //url: "blog/wp-content/plugins/visitor_stat/stats-operations.php",
                      url: "/blog/wp-admin/admin.php?page=visitor_stat/stats-operations.php",                     
                        data: "type=all",
                        success: function(msg)
                        {
                            alert(msg);
                            part = msg.split('#');
                            $("#todays_visit").ajaxComplete(function(event, request, settings)
                            {
                                $("#todays_visit").html(part[0]);
                            });
                            $("#overall_visit").ajaxComplete(function(event, request, settings)
                            {
                                $("#overall_visit").html(part[1]);
                            });
                            $("#todays_visit_plus").ajaxComplete(function(event, request, settings)
                            {
                                $("#todays_visit_plus").val(part[2]);
                            });

                            $("#overall_visit_plus").ajaxComplete(function(event, request, settings)
                            {
                                $("#overall_visit_plus").val(part[3]);
                            });
                            $("#popupDatepicker").ajaxComplete(function(event, request, settings)
                            {
                                $("#popupDatepicker").val(part[4]);
                            });

                        }
                    });



                }

                function saveData(){
                    $.ajax
                    ({
                        type: "POST",
                        url: "/blog/wp-admin/admin.php?page=visitor_stat/stats-operations.php",
                       //url: "blog/wp-content/plugins/visitor_stat/stats-operations.php",
                        data: "type=save&d1="+d1+"&d2="+d2+"&d3="+d3,
                        success: function(msg)
                        {
                            alert(msg);
                            loadData();
                            $("#msg_save").ajaxComplete(function(event, request, settings)
                            {
                                $("#msg_save").html(msg);
                                setTimeout('',10000);
                                $("#msg_save").html('&nbsp;').fadeIn('swing');

                            });

                        }
                    });



                }

                loadData();  // For first time page load default results

                $('#save').live('click',function(){
                    d1=$('#todays_visit_plus').val();
                    d2=$('#overall_visit_plus').val();
                    d3=$('#popupDatepicker').val();
                    saveData(d1,d2,d3);

                }); 



            });

But when I run the file in wordpress admin it shows the internal server error for admin.php?page=visitor_stat/stats-operations.php /blog/wp-admin and it doesn't load the ajax page 但是当我在wordpress admin中运行该文件时,它显示了admin.php的内部服务器错误?page = visitor_stat / stats-operations.php / blog / wp-admin并且它没有加载ajax页面

I tried for several time and I can't find the solution. 我试了好几次,但找不到解决办法。 I think this issue may have correct solution. 我认为这个问题可能有正确的解决方案。 Anybody can help me to solve this issue. 任何人都可以帮我解决这个问题。

Clearly, the ajax function URL : POST is not working. 显然,ajax函数URL:POST不起作用。 Thanks in advance to solve this problem 提前谢谢解决这个问题

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. 首先,为了完成这项任务,建议注册然后将jQuery脚本排入队列,将脚本推送到服务器。 These operations will be hooked in wp_enqueue_scripts action hook. 这些操作将挂钩在wp_enqueue_scripts动作钩子中。 In the same hook you should put wp_localize_script that it's used to include arbitrary Javascript. 在同一个钩子中你应该把它用于包含任意Javascript的wp_localize_script By this way there will be a JS object available in front end. 通过这种方式,前端将有一个JS对象。 This object carries on the correct url to be used by the jQuery handle. 该对象继续使用jQuery句柄使用的正确url。

Please take a look to: 请看看:

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

add these functions to plugin file. 将这些函数添加到插件文件中。

add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
function so_enqueue_scripts(){
  wp_register_script( 'ajaxHandle', get_template_directory_uri() . 'PATH TO YOUR SCRIPT 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',
    action: 'myaction' // this is the function in your functions.php that will be triggered
    data:{ 
      name: 'John',
      age: '38'
    },
    success: function( data ){
      //Do something with the result from server
      console.log( data );
    }
  });
});

Finally on your plugin file there should be the function triggered by your ajax call. 最后在你的插件文件中应该有你的ajax调用触发的函数。 Remember the suffixes: 记住后缀:

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

These suffixes plus the action compose the name of your action: 这些后缀加上操作组成了您的操作名称:

wp_ajax_myaction or wp_ajax_nopriv_myaction 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
}

Hope it helps! 希望能帮助到你!

Let me know if something is not clear. 如果有什么不清楚,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM