javascript 为什么传递到服务器的真实价格在另一个页面中不能正确显示?[关闭]

wqsoz72f  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(83)

**关闭。**此题需要debugging details。目前不接受答复。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
11小时前关闭
Improve this question
我有一个产品页面,我不知何故,它收集产品标题,许可证,价格在'有效载荷',但我认为变量总是保持不变,就像它的硬编码-例如。如果我在下拉菜单中按下Stems的许可证,它已经将总价格更改为该价格,但当我将其添加到购物车并单击购物车中的“继续”按钮时,它会转到checkout.html,但始终存在Enjoy $20 MP3,而不是我添加到购物车中的值,我认为在有效载荷中的productPrice不会自行更改。这是我的产品页面:

<!DOCTYPE html>
      <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Deni Beatz - Beat for price that fit your budget</title>
          <link rel="stylesheet" href="css/product.css">
      
          <script src="./payment.js"></script>
          <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
            rel="stylesheet">
          <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
        </head>
    <body>
            
        <header>
          <!--Nav-->
          <div class="nav container">
            <a href="">Deni Beatz</a>
            <!--Cart Icon-->
            <i class="bx bx-shopping-bag" id="cart-icon"></i>
            <div class="notification" id="cart-notification">0</div>
            <!--Cart-->
            <div class="cart">
              <h2 class="cart-title">Your Cart</h2>
              <!--Content-->
              <div class="cart-content">
                <div class="cart-content">
                  
                </div>
              </div>
              <!--Total-->
              <div class="total">
                <div class="total-title">Total</div>
                <div class="total-price" id="total-price total">$0</div>
              </div>
              <!--Buy Button-->
              <form action="checkout.html">
              <button type="button" class="btn-buy">Continue to purchase</button>
              </form>
              <!--Cart Close-->
              <i class="bx bx-x" id="close-cart"></i>
              <!-- Continue to purchase button moved here -->
            </div>
          </div>
        </header>

            <section id="prodetails" class="section-p1">
              <div class="productcontainer" id="enjoy">
                  <div class="single-pro-image">
                    <img src="./data/high.png"  width="100%" id="product-image" class="product-img">
                  </div> <!--Image resource cant be found - I should go to folder above server and under client directory , because all images and audios are in data folder , root folder is client folder-->
                  
                  <div class="single-pro-details" action="C:\s\starter-ruby\client\checkout.html">
                    <h4 class="product-title" id="title">Enjoy</h4>
                    <h2 id="price" class="price">$20</h2>
                    <h3>Select Licence</h3>
                    <select id="select" class="licence">
                      <option>MP3</option>
                      <option>Tagged Wav</option>
                      <option>Un-Tagged Wav</option>
                      <option>Stems</option>
                      <option>Exlusive</option>
                    </select>
      
                      <script>
                        let select = document.getElementById('select');
                        let price = document.getElementById('price');
      
                        // Prices
                        let prices = {
                          "MP3": '$20',
                          "Tagged Wav": '$27',
                          "Un-Tagged Wav": '$30',
                          "Stems": '$120',
                          "Exlusive": '$300'
                        }
      
                        // When the value of select changes, this event listener fires and changes the text content of price to the coresponding value from the prices object
                        select.addEventListener('change', () => {
                          price.textContent = prices[select.value];
                        });
                      </script>
                      <button class="add-cart">Add To Cart <i class='bx bx-cart-add add-cart'></i></button>
                      <h4>Product Details</h4>
                      <span>Lil Tjay x Trap Type Beat - "Enjoy" in key D# Minor and 160 BPM,It has vibe of Lil Tjay , Pop Smoke and more , Prices are great for this type of beat;Tagged Mastered MP3 for $25,$27 for Tagged Unmastered Wav,$30 for Untagged unmastered Wav,$70 for Stems and $120 for Exlusive</span>
                  </div>
                  <div id="audio">
                      <audio controls style="width:100%;" id="audio-clip">
                          <source src="./data/Enjoy 160 x D sharp minor (1).mp3" type="audio/mp3">
                      </audio>
                  </div>
                </section> 

                <script>
                  // Step 1: Retrieve the necessary information
                  const productTitle = document.querySelector('#title').textContent;
                  const productPrice = document.querySelector('#price').textContent;
                  const selectLicense = document.getElementById('select').value;
                  // Image - not used variable
                  // Audio - not used variable
                
                  // Step 2: Create the payload to send to the server
                  const payload = {
                    title: productTitle,
                    price: productPrice,
                    license: selectLicense,
                    // Image
                    // Audio
                  };
                
                  // Step 3: Make an AJAX request to the server endpoint
                  fetch('/add-to-cart', {
                    method: 'POST',
                    headers: {
                      'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload)
                  })
                    .then(response => {
                      if (response.ok) {
                        // Handle successful response
                        console.log('Item added to cart');
                      } else {
                        // Handle error response
                        console.error('Failed to add item to cart');
                      }
                    })
                    .catch(error => {
                      // Handle network error
                      console.error('Network error', error);
                    });
                </script>
                
                <!--Rest of the code-->

这是我的结帐页面:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./payment.js"></script>

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>

<body>

<style>
  /* Styles for the cart items container */

#product-items {
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 20px;
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

/* Styles for each product details container */

.product-details {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  width: 100%;
}

.product-details img {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
}

/* Styles for the product title */

.product-details h3:first-child {
  margin-top: 0;
}

/* Styles for the total price container */

#total {
  font-weight: bold;
  font-size: 20px;
  margin-top: 20px;
  text-align: center;
}

/* Styles for the continue to payment button */

button {
  background-color: #4c5baf;
  border: none;
  color: white;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  display: block;
  font-size: 16px;
  margin: 0 auto;
  margin-top: 20px;
  cursor: pointer;
}

#buy-btn {
  background-color: #4c5baf;
  border: none;
  color: white;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  font-size: 16px;
  margin: 0 auto;
  margin-top: 20px;
  cursor: pointer;
}
#clear-button {
  background-color: #4c5baf;
  border: none;
  color: white;
  padding: 10px 20px;
  text-align: center;
  text-decoration: none;
  font-size: 16px;
  margin: 0 auto;
  margin-top: 20px;
  cursor: pointer;
}

#buy-btn.non-active {
  display: block;
}

/* Styles for the continue to payment button when hovered */

button:hover {
  opacity: 0.8;
}

#audio {
  display: block;
  margin: 0 auto;
  text-align: center;
  padding-top: 10px;
}
</style>

  <h2 style="text-align:center;">Checkout</h2>
  <div id="product-items">
    <p style="text-align:center;"><span id="added-products"></p>
    <div class="product-container">
      <div id="cart-items"></div>
    </div>
    <button id="clear-button">CLEAR ITEMS - REDIRECT TO HOME</button>
<script>
  // Clear Button function
  document.getElementById("clear-button").addEventListener("click", function() {
  const cartItemsDiv = document.querySelector(".cart-items");
  cartItemsDiv.innerHTML = ""; // clear the HTML content of the cart-items div
  const subtotalSpan = document.getElementById("subtotal");
  const totalSpan = document.getElementById("total");
  subtotalSpan.innerHTML = "";
  totalSpan.innerHTML = "$0"; // set the total price to $0
  
  localStorage.removeItem("selectedItems"); // remove the selected items from localStorage
  clearCartItems();
});
</script>
  </div>

  <div class="total">
    <h3 style="text-align:center; display: none;">Subtotal: <br><span id="subtotal"></span></h3>
    <h3 style="text-align:center;">Total: <br><span id="total" class="checkout-total">$0</span></h3>
    <a><button type="submit" class="buy-button" style="background-color: rgb(29, 4, 216);">Continue to purchase</button></a>
    <a onclick="alert('You will be redirected to the home page')"><button style="background-color: rgb(216, 4, 4);">Cancel</button></a>
  </div>
  <!--It does clear but wonder , make that you cant click on button if that function is done-->
</body>
<script>
  fetch('/cart-items')
    .then(response => response.json())
    .then(data => {
      const cartItems = data.items;
      const cartItemsContainer = document.querySelector('#cart-items');

      // Step 2: Generate HTML elements to display cart items
      cartItems.forEach(item => {
        const itemContainer = document.createElement('div');
        itemContainer.classList.add('cart-item');

        const itemTitle = document.createElement('h3');
        itemTitle.textContent = item.title;

        const itemPrice = document.createElement('p');
        itemPrice.textContent = item.price;

        // Make that it also create img element with that src

        // Make that it also create audio element with that src
        const itemLicense = document.createElement('p');
        itemLicense.textContent = item.license; // Display the license

        itemContainer.appendChild(itemTitle);
        itemContainer.appendChild(itemPrice);
        itemContainer.appendChild(itemLicense); 
        cartItemsContainer.appendChild(itemContainer);
      });
    })
    .catch(error => {
      console.error('Failed to fetch cart items', error);
    });
  const continueButton = document.querySelector(".buy-button");

  continueButton.addEventListener("click", function(event) {
    event.preventDefault();

    // Step 4: Retrieve the total amount from the span element
    const totalElement = document.querySelector("#total");
    const totalAmount = totalElement.textContent.replace("$", "");

    // Step 5: Redirect to the Ruby server endpoint for payment with the total amount
    window.location.href = `http://localhost:4242/payment?total=${totalAmount}`;
  });
</script>
</html>

这是我的ruby,我已经建立了stripe payment,但必须做一些更改:

# frozen_string_literal: true
  require 'stripe'
  require 'sinatra'
  require 'dotenv'
  require 'mail'
  require 'nokogiri'
  require 'open-uri'
  require 'logger'
  require 'json'
  enable :sessions  

  # Replace if using a different env file or config
  Dotenv.load

  # For sample support and debugging, not required for production:
  Stripe.set_app_info(
    'stripe-samples/<name-of-sample>/[<name-of-integration-type>]',
    version: '0.0.1',
    url: 'https://github.com/stripe-samples'
  )
  Stripe.api_version = '2020-08-27'
  Stripe.api_key = ENV['STRIPE_SECRET_KEY']

  set :static, true
  set :public_folder, File.join(File.dirname(__FILE__), ENV['STATIC_DIR'])
  set :port, 4242

  # Define a global array to store the products added to cart
  $cart_items = []

  # Define a route to add products to the cart
  # post '/cart' do
  #   request.body.rewind
  #   product = JSON.parse(request.body.read)
  #   $cart_items.push(product)
  #   content_type :json
  #   { cart_size: $cart_items.size }.to_json
  # end

  # Will need to add up all the prices , calculate that to cents and display it in some div of chekout page 

  post '/add-to-cart' do
    request.body.rewind
    product = JSON.parse(request.body.read)
    $cart_items.push(product)
    content_type :json
    { cart_size: $cart_items.size }.to_json
  end

  # Step 7: Define a route to retrieve the cart items
  get '/cart-items' do
    content_type :json
    { items: $cart_items }.to_json
  end
  
  # Define a route to get the cart items
  get '/cart' do
    content_type :json
    $cart_items.to_json
  end
  
    # Create a new logger instance that logs to a file named 'development.log'
    logger = Logger.new('C:\s\starter-ruby\server\logs/development.log')
  
    # Set the logger to be used by Sinatra
    set :logger, logger

    get '/' do
      logger.info 'Hello World!'
      content_type 'text/html'
      send_file File.join(settings.public_folder, 'index.html')
    end
  
    get '/config' do
      content_type 'application/json'
      {
        publishableKey: ENV['STRIPE_PUBLISHABLE_KEY'],
      }.to_json
    end    

    # Example implementation of calculate_total_amount method

    post '/create-payment-intent' do
      total_amount = calculate_total_amount()

      payment_intent = Stripe::PaymentIntent.create({
        amount: total_amount,
        currency: 'usd',
        automatic_payment_methods: { enabled: true }
      })

      { clientSecret: payment_intent.client_secret }.to_json
    end       

    post '/webhook' do
      # You can use webhooks to receive information about asynchronous payment events.
      # For more about our webhook events check out https://stripe.com/docs/webhooks.
      webhook_secret = ENV['STRIPE_WEBHOOK_SECRET']
      payload = request.body.read
      if !webhook_secret.empty?
        # Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
        sig_header = request.env['HTTP_STRIPE_SIGNATURE']
        event = nil
    
        begin
          event = Stripe::Webhook.construct_event(
            payload, sig_header, webhook_secret
          )
        rescue JSON::ParserError => e
          # Invalid payload
          status 400
          return
        rescue Stripe::SignatureVerificationError => e
          # Invalid signature
          puts '⚠️  Webhook signature verification failed.'
          status 400
          return
        end
      else
        data = JSON.parse(payload, symbolize_names: true)
        event = Stripe::Event.construct_from(data)
      end
    
      case event.type
      when 'payment_intent.succeeded'
        puts '💰  Payment received!'
      end
    
      content_type 'application/json'
      {
        status: 'success'
      }.to_json
    end
rekjcdws

rekjcdws1#

数据被存储为数据的“类型”。它可以是许多格式,例如。char,blob,integer,double,string...这样的例子不胜枚举。不同的“语言”根据数据如何传递给它以及它将如何存储来处理类型,并将根据该类型的定义返回数据。这是预先定义的,例如。就像在SQL表中设置字段类型一样。当数据被访问时,数据将根据该类型发送回,除非在此过程沿着要求更改它。调用数据的应用程序需要通过自己的方式确认数据的类型与它想要看到的相匹配。如果没有,它需要将其格式化为所需的类型,然后显示它或将其交给另一个应用程序。

相关问题