admin管理员组

文章数量:1418021

I have the following script for ajax. this gets the public key and sends all other detail to Stripe server for payment but I need to send the dynamic value of price to item_line.

fetch("/config/")
.then((result) => { return result.json();})
.then((data) => {
  // Initialize Stripe.js
  var data1 = $('#priceId').html();


  const stripe = Stripe(data.publicKey);
  // Event handler
  let submitBtn = document.querySelector("#submitBtn");
  if (submitBtn !== null) {
    submitBtn.addEventListener("click", () => {
      var d = $('#priceId').html();
      console.log(d) // this value need to send to my view...
      
    fetch("/create-checkout-session/")
      .then((result) => { 
        return result.json();
       })
      .then((data) => {
        // Redirect to Stripe Checkout
        return stripe.redirectToCheckout({sessionId: data.sessionId})
      })
      .then((res) => {
        console.log(res);
      });
    });
  }
});

how can I pass and how can I catch in a view file? my current view is:


@csrf_exempt
def create_checkout_session(request):
    if request.method == 'GET':
        domain_url = 'http://localhost:8000/'
        stripe.api_key = settings.STRIPE_SECRET_KEY
        try:
            checkout_session = stripe.checkout.Session.create(
                client_reference_id=request.user.id if request.user.is_authenticated else None,
                success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
                cancel_url=domain_url + 'cancel/',
                payment_method_types=['card'],
                mode='subscription',
                line_items=[
                    {
                        'price': settings.STRIPE_PRICE_ID, # here need dynamic selected value
                        'quantity': 1,
                    }
                ]
            )
            return JsonResponse({'sessionId': checkout_session['id']})
        except Exception as e:
            return JsonResponse({'error': str(e)})


please help me.

I have the following script for ajax. this gets the public key and sends all other detail to Stripe server for payment but I need to send the dynamic value of price to item_line.

fetch("/config/")
.then((result) => { return result.json();})
.then((data) => {
  // Initialize Stripe.js
  var data1 = $('#priceId').html();


  const stripe = Stripe(data.publicKey);
  // Event handler
  let submitBtn = document.querySelector("#submitBtn");
  if (submitBtn !== null) {
    submitBtn.addEventListener("click", () => {
      var d = $('#priceId').html();
      console.log(d) // this value need to send to my view...
      
    fetch("/create-checkout-session/")
      .then((result) => { 
        return result.json();
       })
      .then((data) => {
        // Redirect to Stripe Checkout
        return stripe.redirectToCheckout({sessionId: data.sessionId})
      })
      .then((res) => {
        console.log(res);
      });
    });
  }
});

how can I pass and how can I catch in a view file? my current view is:


@csrf_exempt
def create_checkout_session(request):
    if request.method == 'GET':
        domain_url = 'http://localhost:8000/'
        stripe.api_key = settings.STRIPE_SECRET_KEY
        try:
            checkout_session = stripe.checkout.Session.create(
                client_reference_id=request.user.id if request.user.is_authenticated else None,
                success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
                cancel_url=domain_url + 'cancel/',
                payment_method_types=['card'],
                mode='subscription',
                line_items=[
                    {
                        'price': settings.STRIPE_PRICE_ID, # here need dynamic selected value
                        'quantity': 1,
                    }
                ]
            )
            return JsonResponse({'sessionId': checkout_session['id']})
        except Exception as e:
            return JsonResponse({'error': str(e)})


please help me.

Share Improve this question asked Dec 15, 2020 at 16:09 BikashSaudBikashSaud 3344 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Many ways, I'll give a simple example:

script.js

// wrap request in a function:
function send_data() {
  
  $.ajax({
    url : 'the_url',
    data : {
      'csrfmiddlewaretoken' : '<the-token>',
      'key1' : 'val1',
    },
    method : 'POST',
    success : success_function // reference to below
  });

}

// trigger send_data on some event:
$('<the-selector').on('<some-event>', {}, send_data);

// i.e. send data on button click:
$('#button-id').on('click', {}, send_data);

// success function:
function success_function(response) {

  // unpack response:
  val2 = response.key2;

  // do some logic:
  ...

}

views.py

def my_view_function(request):

    # unpack request from front end:
    val1 = request.POST['key1']

    # do some logic:
    ...

    # pack response:
    response = {
        'key2' : 'val2',
    }

    return JsonResponse(response)

本文标签: javascriptHow to pass data from ajax to django viewStack Overflow