javascript - jquery-ajax 将html元素值从一个页面传递到另一个页面
问题描述
我已经使用 angularJS routing 构建了一个单页应用程序。我有一个购物车页面,用户在其中选择了产品并可以继续结帐。
如果您单击按钮,您将被重定向到结帐页面。
问题是我对总成本进行了硬编码,我想使用 jquery 或 ajax 将其从产品页面传递到结帐页面。我显然可以使用 localstorage 但如果我切换回我的产品页面并编辑价格然后返回结帐,因为没有重新加载发生 localstorage 显示以前的总数。这就是我需要 jquery 或 ajax 解决方案的原因。
我的代码:
//-----Click Checkout button ------
$("#checkOut").click(()=>{
//get count of products
var numOfProducts = $('.product-columns').length;
if(numOfProducts!=0){
//pass total cost to variable
var total = $('.FinalTotal').text();
//append total cost to html total cost element of checkout.php
window.location.href='../php/index.php#!/purchase';
}else{
alert("Your cart is empty");
}
});
来自 products.php 的总计
<p> Total </p>
<span class="new__price FinalTotal">$0</span>
<a href="" id ="checkOut">PROCEED TO CHECKOUT</a>
购买.php
<h2 id = "totalPrice"> Total Price : </h2>
单页应用程序的 angularjs 路由
app.config(($routeProvider)=>{
$routeProvider
.when("/" , {templateUrl:"main.php"})
.when("/login" , {templateUrl : "login.php"})
.when("/register" , {templateUrl : "register.php"})
.when("/results" , {templateUrl : "showResults.php"})
.when("/purchase", {templateUrl:"purchase.php"})
.when("/cart" ,{templateUrl:"products.php"});
});
解决方案
在页面之间传递数据有多种方式:
- 在路线中使用参数。
由于您已经在使用 $routeProvider,因此无需导航,window.location.href,
您可以使用$location.path.
app.config(($routeProvider)=>{
$routeProvider
.when("/" , {templateUrl:"main.php"})
.when("/login" , {templateUrl : "login.php"})
.when("/register" , {templateUrl : "register.php"})
.when("/results" , {templateUrl : "showResults.php"})
.when("/purchase/:cost", {templateUrl:"purchase.php"}) //add the cost as the route param.
.when("/cart" ,{templateUrl:"products.php"});
});
现在,当路由到您的购买页面时:
$location.path('/purchase/'+cost);
在您的购买控制器中,注入 $routeParams 并访问成本:
app.controller('purchaseController', function($scope,$routeParams) {
$scoope.totalCost = $routeParams.cost;
});
您可以使用可以在一个控制器中设置成本值并在另一个控制器中访问它的服务。
var app = angular.module('yourModule',[]); app.service("dataService",function(){ var totalCost = ""; setCost: function(cost){ totalCost = cost; }, getCost: function(){ return totalCost; } });
在您的产品控制器中,注入 dataService 并使用 setCost 方法。
app.controller('productsController', function($scope, dataService) {
dataService.setCost(totalCost);
});
接下来,在您的 PurchaseController 中,访问该值:
app.controller('purchaseController', function($scope, dataService) {
$scope.totalCost = dataService.getCost();
});
推荐阅读
- amazon-s3 - Rundeck S3 插件
- php - Twig 中的 PHP for 循环
- typescript - 打字稿如何重写接口的属性类型
- java - 如何直接在 JDL 中加密 JHIPSTER 应用程序的数据?
- c# - 如何统一更新gps?
- java - 在 Mockito 的测试方法中忽略非无效方法
- java - 命令“echo no | android create avd --force -n test -t android-22 --abi armeabi-v7a”失败并在期间以 1 退出
- python - 如何使用字典变量制作多个子图?
- hadoop - Hadoop 数据节点因消息“无法加载 libhadoop”而关闭
- mvvm - UWP TimePicker MVVM