簡體   English   中英

使用Ajax調用的wordpress PHP

[英]wordpress PHP with Ajax call

我正在尋找通過Wordpress通過Ajax將用戶數據作為字符串返回的方式

iv把基本概念記下來

的PHP

這放在我的functions.php中

 add_action('template_redirect', 'edit_user_concept'); function edit_user_concept(){ $id = $_POST['getbyID']; $user_info = get_userdata($id); echo 'Username: ' . $user_info->user_login . "\\n"; echo 'User roles: ' . implode(', ', $user_info->roles) . "\\n"; echo 'User ID: ' . $user_info->ID . "\\n"; } 

jQuery / JS

  $.ajax({ url: "http://www.example.com/", method: "POST", data: { getbyID: "23", }, success: function(response){ console.log(response); //example script logic here } }) 

控制台日志結果是正確的,但是它還會記錄許多未包含在其中的html元素。

我不完全清楚為什么。

這是一個完整的小例子

 Username: someusername User roles: subscriber User ID: 23 <!DOCTYPE html> <html lang="en-US"> <div id="loadtheme" class="loadtheme"></div> <head> etc etc etc.... 

有什么想法嗎?

回聲后嘗試退出或返回。我不知道完整的問題,但希望對您有所幫助

add_action('template_redirect', 'edit_user_concept');
    function edit_user_concept(){
          $id = $_POST['getbyID'];
          $user_info = get_userdata($id);
          echo 'Username: ' . $user_info->user_login . "\n".'User roles: ' . implode(', ', $user_info->roles) . "\n".'User ID: ' . $user_info->ID . "\n";
          exit;
    }

您正在回顯html而不在任何地方停止它,您可以在此處使用json響應,對於json ,首先需要在ajax請求中使用dataType: "json"

 url: "http://www.example.com/",
 method: "POST",
 dataType: "json" // need to use datatype here.
 data: {
     getbyID: "23",
 }

現在,您需要將數據存儲在PHP中的array中,如下所示:

$result = array();
$result['Username'] = $user_info->user_login;
$result['User_roles'] = implode(', ', $user_info->roles);
$result['User_id'] = $user_info->ID;

現在,您可以使用json_encode()

echo json_encode($result);

您可以像這樣打印json結果:

console.log(response.Username); // will print username
console.log(response.User_roles); // will print user roles
console.log(response.User_id); // will print user id

完整的例子:

$.ajax({
     url: "http://www.example.com/",
     method: "POST",
     dataType: "json" // json data type
     data: {
         getbyID: "23",
     },
     success: function(response){
         console.log(response.Username);
         console.log(response.User_roles);
         console.log(response.User_id);
         //example script logic here
     }
 });

PHP:

<?php
function edit_user_concept(){
  $id = $_POST['getbyID'];
  $user_info = get_userdata($id);
  $result = array();
  $result['Username'] = $user_info->user_login;
  $result['User_roles'] = implode(', ', $user_info->roles);
  $result['User_id'] = $user_info->ID;
  echo json_encode($result); // will return json response
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM