Jquery Step00-$.Ajax Json

本文介绍了一个具体的案例,使用Ajax与jQuery从服务器获取JSON格式的数据,并展示了如何解析这些数据并将其显示在前端页面上。具体实现包括服务器端采用ashx文件处理请求及返回数据,客户端使用jQuery的getJSON方法获取数据并展示。

 

1.json :Newtonsoft.Json http://files.cnblogs.com/ie421/Json20.zip

2.js:jQuery  

3.服务器端:ashx

 public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string method = context.Request.Params["m"];

            if(method=="test")
                context.Response.Write(GetPersonListJosnString_2());
        }

    返回:{"ID":1,"FirstName":"肖","LastName":"永志"}

 

4.前台页面接收

 

    $(document).ready(function(){
        $.getJSON("/ashx/Ajax.ashx",{m:"test"},function(json){
            $.each(json,function(i,item){
                $("#test").append(item.ID+"."+item.FirstName+"<br/>");
            })
        })
    });

 

$(document).ready(function(){
        $.getJSON("/ashx/Ajax.ashx",{m:"test"},function(json){
           
            var tb=$("#tb_name_list");
            tb.find("tr").each(function(i){  //清空表,保留第一行
                if (i>0) $(this).remove();
            });
     
            $.each(json,function(i,item){
                var tr="<tr><td>"+item.ID+"</td><td>"+item.FirstName+"</td><td>"+item.LastName+"</td></tr>";
                tb.append(tr);
            })
        })
    });

<script> jQuery(function($) { // === Helper Functions === function getAjaxUrl() { return (window.wc_cart_params && window.wc_cart_params.ajax_url) || '<?php echo esc_url(admin_url('admin-ajax.php')); ?>'; } function getCartNonce() { const n = $('input[name="woocommerce-cart-nonce"]').val(); return n || '<?php echo wp_create_nonce('woocommerce-cart'); ?>'; } function fmtRM(n) { return 'RM' + (isNaN(n) ? 0 : n).toFixed(2); } // === 全选同步功能 === function syncSelectAllStatus() { // 获取当前所有商品是否都被选中 const allChecked = $('.item-checkbox').length === $('.item-checkbox:checked').length; // 更新表头和页脚的全选状态 $('#select-all-items-header').prop('checked', allChecked); $('#select-all-items-footer').prop('checked', allChecked); } // === 更新选中商品摘要 === function updateSelectedSummary() { let count = 0, total = 0; $('.item-checkbox:checked').each(function() { const quantity = parseFloat($(this).data('quantity')) || 1; const price = parseFloat($(this).data('price')) || 0; count += quantity; total += price; }); $('#selected-count').text(count); $('#selected-total').text(fmtRM(total)); // 同步全选状态 syncSelectAllStatus(); } // === 保存数量修改 === function saveQuantityAjax($input, showNotice = true) { if (!$input || !$input.length) return; const $row = $input.closest('tr'); const cart_item_key = $row.find('.item-checkbox').val(); const newQty = parseFloat($input.val()) || 1; $input.prop('disabled', true); $row.find('.plus, .minus').prop('disabled', true); const payload = { action: 'update_cart_item_qty', security: getCartNonce(), cart_item_key: cart_item_key, qty: newQty }; $.post(getAjaxUrl(), payload, function(response) { if (response && response.success) { const d = response.data || {}; const $checkbox = $row.find('.item-checkbox'); // 更新小计列的HTML if (d.subtotal_html) { $row.find('.product-subtotal').html(d.subtotal_html); } // 更新复选框的数据 if (d.discounted_price) { $checkbox.data('price', d.discounted_price); $checkbox.attr('data-price', d.discounted_price); } else if (d.subtotal_html) { const priceValue = parseFloat( d.subtotal_html.replace(/[^\d.]/g, '') .replace(/\.(?=.*\.)/g, '') .replace(/,/g, '') ); if (!isNaN(priceValue)) { $checkbox.data('price', priceValue); $checkbox.attr('data-price', priceValue); } } if (d.unit_price) { $checkbox.data('unit-price', d.unit_price); $checkbox.attr('data-unit-price', d.unit_price); } // 更新数量属性 if (d.adjusted_qty) { $input.val(d.adjusted_qty); $checkbox.data('quantity', d.adjusted_qty); $checkbox.attr('data-quantity', d.adjusted_qty); } // 更新库存属性 if (d.max_stock) { $input.attr('max', d.max_stock); $input.attr('data-stock', d.max_stock); } // 显示通知 if (showNotice && d.notice) { alert(d.notice); } // 更新摘要 updateSelectedSummary(); } }).always(function() { $input.prop('disabled', false); $row.find('.plus, .minus').prop('disabled', false); }); } // === 处理库存超量 === function handleOverstock($input) { const maxStock = parseInt($input.attr('data-stock')) || 0; const currentQty = parseInt($input.val()) || 0; if (maxStock > 0 && currentQty > maxStock) { $input.val(currentQty); alert(`此商品库存仅剩 ${maxStock}`); $input.val(maxStock); saveQuantityAjax($input, false); return true; } return false; } // === 心愿单功能 === function handleWishlistClick(e) { e.preventDefault(); const $btn = $(this); const productId = $btn.data('product-id'); const isInWishlist = $btn.hasClass('in-wishlist'); if (isInWishlist) { // 前往心愿单页面 window.location.href = 'https://animangabookstore.com/wishlist/'; } else { // 添加到心愿单 $btn.find('.heart-icon').css('opacity', '0.5'); $.post(getAjaxUrl(), { action: 'add_to_wishlist', security: getCartNonce(), product_id: productId }, function(response) { if (response.success) { $btn.addClass('in-wishlist') .attr('title', '浏览心愿单') .find('.heart-icon') .css('fill', 'red') .css('opacity', '1'); // 更新图标样式 $btn.find('.heart-icon').css({ 'fill': 'red', 'opacity': '1' }); } else { alert(response.data.message || '添加到心愿单失败'); $btn.find('.heart-icon').css('opacity', '1'); } }).fail(function() { $btn.find('.heart-icon').css('opacity', '1'); }); } } // === 事件绑定 === function bindEvents() { // 移除默认的WooCommerce行为 $('body').off('click', '.plus, .minus'); // 数量输入 $('.woocommerce-cart-form').on('input', '.qty', function() { handleOverstock($(this)); }); // 失焦时保存 $('.woocommerce-cart-form').on('blur', '.qty', function() { saveQuantityAjax($(this), true); }); // 按回车键保存 $('.woocommerce-cart-form').on('keydown', '.qty', function(e) { if (e.key === 'Enter') { e.preventDefault(); saveQuantityAjax($(this), true); } }); // +/- 按钮,500ms延迟 $('body').on('click', '.plus,.minus', function(e) { e.stopImmediatePropagation(); const $input = $(this).closest('.quantity').find('input.qty'); const currentQty = parseInt($input.val()) || 0; const step = $(this).hasClass('plus') ? 1 : -1; const newQty = Math.max(1, currentQty + step); $input.val(newQty); if (!handleOverstock($input)) { clearTimeout($input.data('buttonSaveTimer')); $input.data('buttonSaveTimer', setTimeout(() => { saveQuantityAjax($input, true); }, 500)); } }); // 全选功能 $('#select-all-items-header, #select-all-items-footer').change(function() { const isChecked = $(this).prop('checked'); $('.item-checkbox').prop('checked', isChecked); updateSelectedSummary(); }); // 当选择改变时更新摘要 $('.item-checkbox').change(updateSelectedSummary); // 删除选中商品 $('#remove-selected-items').click(function() { const keys = $('.item-checkbox:checked').map(function() { return $(this).val(); }).get(); if (keys.length === 0) { alert('请先选择要删除的商品'); return; } $.post(getAjaxUrl(), { action: 'remove_selected_cart_items', security: getCartNonce(), cart_item_keys: keys }, function(response) { if (response.success) { keys.forEach(function(key) { $(`.item-checkbox[value="${key}"]`).closest('tr').remove(); }); updateSelectedSummary(); } }); }); // 清空购物车 $('#clear-cart').click(function() { if (!confirm('确定要清空整个购物车吗?')) return; $.post(getAjaxUrl(), { action: 'empty_cart', security: getCartNonce() }, function(response) { if (response.success) { $('.woocommerce-cart-form__cart-item').remove(); updateSelectedSummary(); } }); }); // 应用优惠券 $('#apply-coupon').click(function() { const code = $('#coupon_code').val(); if (!code) { alert('请输入优惠券代码'); return; } $.post(getAjaxUrl(), { action: 'apply_coupon', security: getCartNonce(), coupon_code: code }, function(response) { if (response.success) { alert('优惠券应用成功!'); location.reload(); } else { alert(response.data.message || '优惠券应用失败'); } }); }); // 部分结算 $('#partial-checkout').click(function(e) { const keys = $('.item-checkbox:checked').map(function() { return $(this).val(); }).get(); if (keys.length === 0) { e.preventDefault(); alert('请至少选择一件商品结算'); return false; } sessionStorage.setItem('selected_cart_items', JSON.stringify(keys)); return true; }); // 心愿单按钮点击事件 $('body').on('click', '.wishlist-icon', handleWishlistClick); } // === 初始化 === $(document).ready(function() { // 初始化库存属性 $('.item-checkbox').each(function() { const $input = $(this).closest('tr').find('.qty'); const maxStock = parseInt($input.attr('max')) || 0; if (maxStock > 0) { $input.attr('data-stock', maxStock); } }); // 初始更新摘要 updateSelectedSummary(); // 绑定所有事件 bindEvents(); }); }); </script> without changing anything, make these code in formatted way
最新发布
09-19
<script> jQuery(function($){ // === 辅助函数 === function getAjaxUrl(){ return (window.wc_cart_params && window.wc_cart_params.ajax_url) || '<?php echo esc_url(admin_url('admin-ajax.php')); ?>'; } function getCartNonce(){ var n = $('input[name="woocommerce-cart-nonce"]').val(); return n || '<?php echo wp_create_nonce('woocommerce-cart'); ?>'; } function fmtRM(n){ return 'RM' + (isNaN(n) ? 0 : n).toFixed(2); } // === 选中商品统计 === function updateSelectedSummary(){ var count = 0, total = 0; $('.item-checkbox:checked').each(function(){ count += parseFloat($(this).data('quantity') || 1); total += parseFloat($(this).data('price') || 0); }); $('#selected-count').text(count); $('#selected-total').text(fmtRM(total)); } // === 保存数量 AJAX 请求 === function saveQuantityAjax($input, showNotice = true){ if(!$input || !$input.length) return; var $row = $input.closest('tr'); var cart_item_key = $row.find('.item-checkbox').val(); var newQty = parseFloat($input.val()) || 1; $input.prop('disabled', true); $row.find('.plus, .minus').prop('disabled', true); var payload = { action: 'update_cart_item_qty', security: getCartNonce(), cart_item_key: cart_item_key, qty: newQty }; $.post(getAjaxUrl(), payload, function(response){ if(response && response.success){ var d = response.data || {}; var $checkbox = $row.find('.item-checkbox'); // 更新商品信息 if(d.subtotal_html) $row.find('.product-subtotal').html(d.subtotal_html); if(d.line_total_incl_tax) $checkbox.attr('data-price', d.line_total_incl_tax); if(d.unit_price) $checkbox.attr('data-unit-price', d.unit_price); if(d.adjusted_qty) $input.val(d.adjusted_qty); // 更新库存属性 if(d.max_stock) { $input.attr('max', d.max_stock); $input.attr('data-stock', d.max_stock); } // 仅在需要时显示通知 if(showNotice && d.notice) { alert(d.notice); } updateSelectedSummary(); } }).always(function(){ $input.prop('disabled', false); $row.find('.plus, .minus').prop('disabled', false); }); } // === 处理数量增加超过库存的逻辑 === function handleOverstock($input) { var maxStock = parseInt($input.attr('data-stock')) || 0; var currentQty = parseInt($input.val()) || 0; if (maxStock > 0 && currentQty > maxStock) { // 1. 暂时设为超出值 $input.val(currentQty); // 2. 显示警告 alert(`此商品库存仅剩 ${maxStock}`); // 3. 设置为最大库存值 $input.val(maxStock); // 4. 立即保存并禁止显示重复通知 saveQuantityAjax($input, false); return true; } return false; } // === 事件绑定 === function bindEvents() { // 覆盖WooCommerce默认的数量输入行为 $('body').off('click', '.plus, .minus'); // 数量输入事件 - 仅检查库存,不自动保存 $('.woocommerce-cart-form').on('input', '.qty', function() { var $input = $(this); handleOverstock($input); }); // 失去焦点时保存 $('.woocommerce-cart-form').on('blur', '.qty', function() { saveQuantityAjax($(this), true); }); // 回车键事件 $('.woocommerce-cart-form').on('keydown', '.qty', function(e) { if(e.key === 'Enter') { e.preventDefault(); saveQuantityAjax($(this), true); } }); // +/- 按钮事件(添加0.5秒延迟) $('body').on('click', '.plus,.minus', function(e) { e.stopImmediatePropagation(); var $input = $(this).closest('.quantity').find('input.qty'); var currentQty = parseInt($input.val()) || 0; var step = $(this).hasClass('plus') ? 1 : -1; var newQty = Math.max(1, currentQty + step); // 设置新值(即使超过库存) $input.val(newQty); // 处理超过库存的情况 if (!handleOverstock($input)) { // 清除之前的定时器 clearTimeout($input.data('buttonSaveTimer')); // 设置0.5秒后执行的保存定时器 $input.data('buttonSaveTimer', setTimeout(function() { saveQuantityAjax($input, true); }, 500)); // 500毫秒 = 0.5秒 } }); // 初始化全选功能 $('#select-all-items, #footer-select-all').change(function() { var isChecked = $(this).prop('checked'); $('.item-checkbox').prop('checked', isChecked); updateSelectedSummary(); }); $('.item-checkbox').change(updateSelectedSummary); // 删除选中商品 $('#remove-selected-items').click(function() { var keys = $('.item-checkbox:checked').map(function() { return $(this).val(); }).get(); if (keys.length === 0) { alert('请先选择要删除的商品'); return; } $.post(getAjaxUrl(), { action: 'remove_selected_cart_items', security: getCartNonce(), cart_item_keys: keys }, function(response) { if (response.success) { keys.forEach(function(key) { $('.item-checkbox[value="' + key + '"]').closest('tr').remove(); }); updateSelectedSummary(); } }); }); // 清空购物车 $('#clear-cart').click(function() { if (!confirm('确定要清空整个购物车吗?')) return; $.post(getAjaxUrl(), { action: 'empty_cart', security: getCartNonce() }, function(response) { if (response.success) { $('.woocommerce-cart-form__cart-item').remove(); updateSelectedSummary(); } }); }); // 应用优惠券 $('#apply-coupon').click(function() { var code = $('#coupon_code').val(); if (!code) { alert('请输入优惠券代码'); return; } $.post(getAjaxUrl(), { action: 'apply_coupon', security: getCartNonce(), coupon_code: code }, function(response) { if (response.success) { alert('优惠券应用成功!'); } else { alert(response.data.message || '优惠券应用失败'); } }); }); // 部分结算 $('#partial-checkout').click(function(e) { var keys = $('.item-checkbox:checked').map(function() { return $(this).val(); }).get(); if (keys.length === 0) { e.preventDefault(); alert('请至少选择一件商品结算'); return false; } // 保存选中商品到sessionStorage sessionStorage.setItem('selected_cart_items', JSON.stringify(keys)); return true; }); } // === 初始化 === $(document).ready(function() { // 初始化库存属性 $('.item-checkbox').each(function() { var $input = $(this).closest('tr').find('.qty'); var maxStock = parseInt($input.attr('max')) || 0; if(maxStock > 0) { $input.attr('data-stock', maxStock); } }); updateSelectedSummary(); bindEvents(); }); }); </script> When manually input quantity exceeds maximum available quantity, it triggers the notice instantly when i key in the number. Can you delay it? like only trigger when its saving the quantity entered, not directly when i enter amount bigger than maximum available amount
09-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值