dongpa3109 2016-10-23 14:07
浏览 125
已采纳

Wordpress AJAX:获取Json响应的功能

I'd like to get a function as Json response in my Ajax call, after the document is ready. I'm not sure if I'm on the right way but here is what I did so far:

My Html

<!--Where i want to load my function-->
<div id="applications"></div>

My Ajax/Jquery

jQuery(document).ready(function(){
    init_applications();
});
function init_applications(){
    var app_data = new FormData();
    app_data.append('action', 'applications');
    app_data.append('uid', uid);
    app_data.append('pid', pid);
    jQuery.ajax({
        method: 'post',
        url: ajaxurl,
        dataType: 'json',
        data: app_data,
        processData: false,
        contentType: false,
        beforeSend:function(data){
            //something
        },
        success:function(data) {
            $('#applications').html(data.htmlapp);
            //console.log(data);
        },
        error: function(data){
            //console.log(data);
        }
    });
    //alert("a");
}

Of course in my functions.php

add_action('wp_ajax_applications', 'applications');
function applications(){
    $uid = $_POST['uid'];
    $pid = $_POST['pid'];
    $applications = inside_applications();
    $response = array('htmlapp'=>$applications);
    wp_send_json( $response );
}

and Finally I've created my separate function always in functions.php

function inside_applications(){
   //Some html code and instructions
}

Is this possible or I'm totally out of the way? Can you please give me some directions eventually? Many thanks.

  • 写回答

1条回答 默认 最新

  • dqajyxqem115006813 2016-10-23 15:00
    关注

    All the previous reasoning was fine, it's just matter to return values or html in the function you want include. In my case was.

    function inside_applications(){
       //Some html code and instructions
       $html = '<div class="something>everything</div>';
       $html .= '<div class="solved">solved</div>';
       //Insert some if or instructions
       return $html;
    }
    

    As discussed in comments wp_send_json() hook already print() and die() so it's not necessary to do anything more. Maybe there are other better methods to accomplish that but my objective was to Ajaxify a Wordpress theme and to have separate multiple functions refreshable and ready for my jQuery calls and actions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化