How to handle jQuery.ajax(..) JSON request ?

本文介绍如何在Wicket框架中利用jQuery.ajax方法处理JSON请求,包括抽象行为实现、请求参数解析和响应数据处理。
 Apache Wicket > Framework Documentation > Reference library > How to do things in Wicket > AJAX > How to handle jQuery.ajax(..) JSON request ?
#editReport()

The following is the jQuery JSON request code

This section of code invokes a abstract behavior ona page with a json request:

console.log(" call back url :"+ callBackURL);
               $.ajax({
                    url: callBackURL,
                    type: 'post',
                    cache: false,

                    data:JSON.stringify(ccbArry),
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function(json) {
                        console.log(" reponse :"+ json);

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log("error :"+XMLHttpRequest.responseText);
                    }
                    

                });

This section of code  is an abstract ajax behavior which accepts a json document in request and responds with another json  document that is then available to the  javascript method on the page. 

        AbstractAjaxBehavior ajaxSaveBehaviour = new AbstractAjaxBehavior(){
            private static final long serialVersionUID = 1L;

            @SuppressWarnings("unchecked")
            public void onRequest()
            {
                //get parameters
                final RequestCycle requestCycle = RequestCycle.get();


                WebRequest wr=(WebRequest)requestCycle.getRequest();

                HttpServletRequest hsr= wr.getHttpServletRequest() ;

                try {
                    BufferedReader br = hsr.getReader();
                
                           String  jsonString = br.readLine();
                           if((jsonString==null) || jsonString.isEmpty()){
                               logger.error(" no json found");
                           }
                           else {
                               logger.info(" json  is :"+ jsonString);
                           }
                            

                
                } catch (IOException ex) {
                    logger.error(ex);
                }


                // json string to retir to the jQuery onSuccess function
                String data=getReturnJSONValue();

                logger.info("returning json :"+ data);
                IRequestTarget t = new StringRequestTarget("application/json", "UTF-8", data);
                getRequestCycle().setRequestTarget(t);


                //requestCycle.setRequestTarget(new StringRequestTarget("application/json", "utf-8", data));
            }


        };
        add(ajaxSaveBehaviour);
       
        String callBackURL= ajaxSaveBehaviour.getCallbackUrl().toString();
        logger.info(" callback url :"+ callBackURL);
AI Overview Implementing selective checkout with checkboxes on a cart page typically involves allowing users to select specific items in their cart for purchase, rather than requiring them to purchase all items. This functionality is not a standard feature in most e-commerce platforms and usually requires custom development or the use of specialized plugins/apps. General Approach: Modify the Cart Template: Add a checkbox next to each item in the cart. Ensure the checkbox is linked to the specific product or line item. Handle User Selections: Use JavaScript to detect changes in checkbox states (checked/unchecked). When a checkbox is selected or deselected, update the cart's subtotal and potentially the items that will be included in the checkout process. Adjust the Checkout Process: When the user proceeds to checkout, ensure that only the items corresponding to the selected checkboxes are passed to the order. This may involve modifying the platform's core checkout logic or using hooks/filters provided by the platform. Platform-Specific Considerations: WooCommerce (WordPress): Requires custom code in functions.php or a custom plugin to add checkboxes, manage selections, and modify the checkout process. You might use AJAX to update the cart dynamically as selections are made. Shopify: Involves modifying theme files (e.g., cart-template.liquid, theme.js) to add checkboxes and JavaScript to handle the logic. This often requires familiarity with Liquid (Shopify's templating language) and JavaScript. Other Platforms: The specific implementation will vary based on the platform's architecture and extensibility options. It may involve similar approaches of template modification and custom code. Important Notes: Complexity: Implementing selective checkout can be complex and may require advanced coding skills. User Experience: Carefully consider the user experience implications of selective checkout to ensure it is intuitive and does not cause confusion. Testing: Thoroughly test the functionality to ensure that selected items are correctly processed and that no loopholes exist (e.g., refreshing the page causing issues with selected items). I want to achieve this selective checkbox function in my cart page. Im using woocommerce and woodmart theme. Please advice on what to do
07-30
It says There has been a critical error on this website. Please review my code cart.php: <?php /** * The template for displaying the cart page. * * This file has been modified to support selective checkout with checkboxes. * * @package woodmart */ defined( 'ABSPATH' ) || exit; do_action( 'woocommerce_before_cart' ); ?> <form class="woocommerce-cart-form" action="<?php echo esc_url( wc_get_cart_url() ); ?>" method="post"> <?php do_action( 'woocommerce_before_cart_table' ); ?> <table class="shop_table shop_table_responsive cart woocommerce-cart-form__contents" cellspacing="0"> <thead> <tr> <th class="product-select"><input type="checkbox" id="select-all-items"> Select All</th> <th class="product-name"><?php esc_html_e( 'Product', 'woocommerce' ); ?></th> <th class="product-price"><?php esc_html_e( 'Price', 'woocommerce' ); ?></th> <th class="product-quantity"><?php esc_html_e( 'Quantity', 'woocommerce' ); ?></th> <th class="product-subtotal"><?php esc_html_e( 'Subtotal', 'woocommerce' ); ?></th> <th class="product-remove"> </th> </tr> </thead> <tbody> <?php do_action( 'woocommerce_before_cart_contents' ); ?> <?php foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key ); if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) { $product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key ); ?> <tr class="woocommerce-cart-form__cart-item <?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>"> <td class="product-select" data-title="<?php esc_attr_e( 'Select', 'woocommerce' ); ?>"> <label> <input type="checkbox" name="selected_items[]" value="<?php echo esc_attr( $cart_item_key ); ?>" checked> </label> functions.php: // Add checkbox to each cart item add_filter('woocommerce_cart_item_name', 'add_checkbox_to_cart_item', 10, 3); function add_checkbox_to_cart_item($item_name, $cart_item, $cart_item_key) { $checked = WC()->session->__isset('selected_items') && in_array($cart_item_key, WC()->session->get('selected_items')) ? 'checked' : 'checked'; $checkbox = '<label><input type="checkbox" name="selected_items[]" value="' . esc_attr($cart_item_key) . '" ' . $checked . '> ' . $item_name . '</label>'; return $checkbox; } // Handle AJAX request to update selected items add_action('wp_ajax_update_selected_cart_items', 'handle_update_selected_cart_items'); add_action('wp_ajax_nopriv_update_selected_cart_items', 'handle_update_selected_cart_items'); function handle_update_selected_cart_items() { if (isset($_POST['selected_items']) && is_array($_POST['selected_items'])) { $selected_items = array_map('sanitize_text_field', $_POST['selected_items']); WC()->session->set('selected_items', $selected_items); foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { if (!in_array($cart_item_key, $selected_items)) { WC()->cart->set_quantity($cart_item_key, 0); } else { WC()->cart->set_quantity($cart_item_key, $cart_item['quantity']); } } wp_send_json_success(); } wp_send_json_error(); } // Only include selected items in order add_filter('woocommerce_add_to_order_from_cart_item', 'filter_items_during_checkout', 10, 3); function filter_items_during_checkout($bool, $cart_item_key, $order) { $selected_items = WC()->session->get('selected_items', []); if (!in_array($cart_item_key, $selected_items)) { return false; } return $bool; } // Reset session after checkout add_action('woocommerce_thankyou', 'reset_selected_items_session'); function reset_selected_items_session($order_id) { WC()->session->__unset('selected_items'); } js/custom-cart.js jQuery(document).ready(function($) { // Add "Select All" checkbox dynamically to cart (only if not already present) if ($('#select-all-items').length === 0) { $('.woocommerce-cart-form__contents').before( '<div class="select-all-wrapper" style="margin: 15px 0;">' + ' <label><input type="checkbox" id="select-all-items"> Select All</label>' + '</div>' ); } // Handle checkbox changes for individual items $(document).on('change', 'input[name="selected_items[]"]', function() { updateSelectedItemsAndSyncCart(); }); // Handle "Select All" checkbox change $(document).on('change', '#select-all-items', function() { var isChecked = $(this).is(':checked'); $('input[name="selected_items[]"]').prop('checked', isChecked); updateSelectedItemsAndSyncCart(); }); // Function to collect selected items and send AJAX request function updateSelectedItemsAndSyncCart() { let selectedItems = []; // Collect selected item keys $('input[name="selected_items[]"]:checked').each(function() { selectedItems.push($(this).val()); }); // Send AJAX request to update cart $.ajax({ url: wc_cart_params.ajax_url, type: 'POST', data: { action: 'update_selected_cart_items', selected_items: selectedItems }, success: function(response) { if (response) { // Refresh cart fragments and update checkout $('body').trigger('wc_fragment_refresh'); $('body').trigger('update_checkout'); // Update "Select All" checkbox state const allCheckboxes = $('input[name="selected_items[]"]'); const checkedCheckboxes = allCheckboxes.filter(':checked'); $('#select-all-items').prop('checked', allCheckboxes.length === checkedCheckboxes.length); } } }); } }); whats wrong?
07-30
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值