【发布时间】:2017-05-25 18:00:26
【问题描述】:
我正在使用两个 div。在第一个 div 中,所有 WordPress 用户都显示在一个页面上,带有“添加”按钮选项。通过添加用户,他们可以使用 Ajax 添加到第二个 div。但我想缓存第二个 div 中显示的结果。用户模板的代码如下-
<?php
/*
Template Name: Users
*/
?>
<style>
.container{
width: 800px;
}
.left{
float:left;
width: 300px;
background: ##66CDAA;
border-right: thick-solid #fff;
}
.right{
overflow: hidden;
width: 300px;
background: powderblue;
}
</style>
<?php
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class="container">
<div class="left" id="xyz">
<table>
<tr>
<th>Name</th>
<th>Gravatar Image</th>
<th>Add to Div</th>
</tr>
<?php
$sql ="SELECT * FROM wp_users";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ){ ?>
<tr>
<td id="<?php echo $result->ID; ?>">
<?php echo $result->display_name; ?>
</td>
<td>
<php echo get_avatar( $result->user_email, 42); ?>
</td>
<td>
<input type="button" class="submit" data-id="<?php echo $result->ID; ?>" data-name="<?php echo $result->display_name; ?>" data_image="<?php echo get_avatar_url($result->user_email, 42); ?>" value="ADD"><p style="display:none;">Added</p>
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="right">
<p>Added Users</p>
<table>
<tr>
<th>Name<th>
<th>Image</th>
</tr>
</table>
</div>
</div>
</main>
</div>
<?php get_footer(); ?>
现在,在 ajax.js 我有以下代码:
(function($) {
$(document).ready(function() {
$(".submit").on("click", function(e){
e.preventDefault();
$(this).css("display", "none");
$(this).closest("td").find("p").css("display", "block");
var id = $(this).data('id');
var name = $(this).data('name);
var image = $(this).data('image');
$.ajax({
url: ajax_url,
method: 'post',
data: { action: 'work', id:id, name: name, image:image},
success: function(response){
var test = jQuery.parseJSON(response);
name1 = test.myname;
url1: test.url;
id: test.id;
$('.table').append('<tr id=" ' + id1+ ' "><td>' + name1 + '</td><br><td><img src=" ' + url1 + ' "></td><td><input type="button" value="Cancel" class="cancel"></td></tr>');
$('.cancel').on("click", function(e){
e.preventDefault();
var id2 =$(this).closest.("tr").attr('id');
$('td[id=' + id2 + ']').closest('tr').find('p').css('display', 'none');
$('td[id=' + id2 + ']').closest('tr').find('input').css('display', 'block');
$(this).closest("tr").hide();
})
}
})
})
})
})(jQuery);
现在,在 ajax.php 中,我有如下功能:
function work() {
$id = $_POST['id'];
$name = $_POST['name'];
$image_url = $_POST['image'];
$myObj->myname = $name;
$myObj->url = $image_url;
$myObj->id = $id;
$myJSON = json_encode($myObj);
echo $myJSON;
wp_die();
}
我想使用 Ajax 将用户添加到第二个 div,并且还想将结果缓存一段时间。另外,建议是否有更好的隐藏添加按钮的方法,或者我是否可以应用条件来检查是否已添加特定用户不应该添加两次。但我的主要问题是如何缓存 ajax 结果。
【问题讨论】:
-
在
localstorage中创建js数组和set/get,同时检查$.inArray()以在将现有用户数据添加到localStorage 之前检查它们
标签: javascript php jquery ajax wordpress