无AJAX调用时jQuery函数返回JSON对象及购物车数据存储问题
Hey there! Let's tackle your two main issues one by one and fix up your code to work as expected.
一、解决cart_items无法正确存储购物车数据的问题
Looking at your code, there are a couple of key issues causing the cart_items variable not to update correctly:
- You're binding the
.plateclick event inside thegetValueUsingClassfunction, which means every time you click a checkbox, a new event listener gets added—leading to duplicate and unexpected behavior. - The callback attempt inside
getValueUsingClassis unnecessary here (since this is a synchronous operation, no async AJAX calls involved), and the way you're trying to updatecart_itemswon't affect the outer variable.
修正后的代码
Here's the cleaned-up client.js that properly updates cart_items and renders the cart details in the modal:
$(document).ready(function () { var cart_items = []; // 单纯获取选中的购物车项,返回数组 function getValueUsingClass() { var chkArray = []; $(".checkboxlist:checked").each(function () { var cart_item = { id: this.id, item: this.name, cost: Number(this.value), quantity: 1 }; chkArray.push(cart_item); }); return chkArray; } // 点击复选框时更新cart_items $(".checkboxlist").click(function () { cart_items = getValueUsingClass(); console.log("Updated cart items:", cart_items); }); // 点击Plate按钮打开模态框时,渲染最新的购物车内容 $(".plate").on('click', function () { // 先更新cart_items为最新选中项 cart_items = getValueUsingClass(); $('.plate_items').html("<ul class='list-group'></ul>"); if (cart_items.length === 0) { $('.plate_items').append("<p>Your cart is empty!</p>"); return; } // 渲染每个购物车项 cart_items.forEach(function(item) { $('.plate_items .list-group').append(`<li class="list-group-item">${item.item} - Rs.${item.cost}</li>`); }); }); // 点击Proceed按钮时合并用户信息 $('.proceed_btn').on('click', function () { // 确保cart_items是最新的 cart_items = getValueUsingClass(); let userDetails = { name: $('#name').val(), email: $('#email').val(), empid: $('#empid').val() }; // 合并到cart_items(或者单独存储,看你的需求) cart_items.push(userDetails); console.log("Final cart with user info:", cart_items); // 这里可以继续处理支付逻辑 }); });
关键修正点
- 分离职责:
getValueUsingClass只负责获取选中的复选框数据并返回数组,不处理事件绑定或DOM渲染。 - 正确更新
cart_items: 因为getValueUsingClass是同步函数(直接读取DOM,没有异步请求),你可以直接把它的返回值赋值给cart_items。 - 避免重复事件绑定: 把
.plate的点击事件绑定移到document.ready里,只绑定一次,每次点击时重新获取最新的购物车数据再渲染。
二、不使用AJAX从jQuery函数返回JSON对象
Since JSON is just a structured data format (objects/arrays in JavaScript), you can directly return a JavaScript object/array from your function—no AJAX needed, as long as the operation is synchronous.
示例1:同步返回JSON对象
If you're pulling data from the DOM or generating it locally, just construct the object and return it:
function getUserInfo() { // 直接构造并返回JSON格式的对象 return { name: $('#name').val(), email: $('#email').val(), empid: $('#empid').val() }; } // 使用时 var userData = getUserInfo(); console.log(userData); // 这就是一个JSON对象
示例2:处理异步操作(如果需要)
If you ever have an asynchronous operation that's not AJAX (like a timeout or file reader), you can use jQuery's Deferred to return a promise:
function getAsyncData() { var dfd = $.Deferred(); // 模拟异步操作 setTimeout(function() { var mockData = { cartTotal: 250, itemsCount: 3 }; dfd.resolve(mockData); // 异步完成后返回数据 }, 1000); return dfd.promise(); } // 使用时 getAsyncData().done(function(data) { console.log("Async data:", data); });
But in your current case, since you're just reading DOM elements synchronously, you don't need Deferred at all—just return the array/object directly.
内容的提问来源于stack exchange,提问作者raju 2192

