如何在Django中使用JSON从数据库获取项目的ID时,应该如何提取项目的ID。

huangapple go评论105阅读模式
英文:

How to fetch the id of an item in Django when using JSON to fetch from the database

问题

以下是代码的翻译部分:

  1. 我有一个Django模板我正在在首页循环遍历多个项目当单击一个项目时应该显示一个模态框我通过导入它来包含它并显示与单击的项目相关的数据我正在使用JSONResponse来预填充模态框一旦模态框显示我想创建一个结账会话需要引用模态框中的项目的ID我卡在如何获取ID
  2. 以下是用于显示模态框和预填充它的脚本
  3. let modal = document.getElementById("modal");
  4. modal.style.display = "none";
  5. function modalHandler(val, content_id) {
  6. if (val) {
  7. let xhr = new XMLHttpRequest();
  8. xhr.onreadystatechange = function () {
  9. if (this.readyState == 4 && this.status == 200) {
  10. let data = JSON.parse(this.responseText);
  11. document.getElementById("subtotal").innerHTML = data.subtotal;
  12. document.getElementById("taxes").innerHTML = data.taxes;
  13. document.getElementById("website_fee").innerHTML = data.website_fee;
  14. document.getElementById("total").innerHTML = data.total;
  15. fadeIn(modal);
  16. }
  17. };
  18. xhr.open("GET", "/modal-content/" + content_id + "/", true);
  19. xhr.send();
  20. } else {
  21. fadeOut(modal);
  22. }
  23. }
  24. 以下是返回JSON数据的views.py
  25. def modal_content_view(request, content_id):
  26. my_model = get_object_or_404(MyModels, content_id=content_id)
  27. print("the model is {my_model.username}")
  28. data = {
  29. 'subtotal': my_model.username,
  30. 'taxes': '2.60',
  31. 'website_fee': '0.87',
  32. 'total': '23.47',
  33. 'content_id': my_model.content_id
  34. }
  35. return JsonResponse(data)
  36. 以下是在单击结账按钮时获取数据的脚本
  37. <script type="text/javascript">
  38. var checkoutButton = document.getElementById('checkout-button');
  39. checkoutButton.addEventListener('click', function() {
  40. fetch("{% url 'checkout' content_id %}", {
  41. method: 'POST',
  42. data: JSON.stringify({
  43. amount: "{{ cost }}" * 100,
  44. description: "{{ title }}",
  45. gig_id: "{{ gig_id }}",
  46. }),
  47. })
  48. .then(function(response) {
  49. return response.json();
  50. })
  51. .then(function(session) {
  52. return stripe.redirectToCheckout({ sessionId: session.id });
  53. })
  54. .then(function(result) {
  55. if (result.error) {
  56. alert(result.error.message);
  57. }
  58. })
  59. .catch(function(error) {
  60. console.error('Error:', error);
  61. });
  62. });
  63. </script>
  64. 以下是处理从上面脚本传递的content_id的视图
  65. @csrf_exempt
  66. def create_checkout_session(request, content_id):
  67. model = MyModels.objects.get(content_id=content_id)
  68. subscription = Subscription(model=model, is_subscribed=False, user=request.user)
  69. 触发模态框显示的onclick函数如下
  70. onclick="modalHandler(true, '{{content.model.content_id}}')"
  71. 我的问题是如何将'content_id'从模态框传递给处理结账的脚本
  72. <details>
  73. <summary>英文:</summary>
  74. I have a Django template whereby I am looping through several items in the homepage. When an item is clicked, a modal which I have included by importing it should be shown and data related to the clicked item displayed. I am using JSONResponse to prepopulate the modal. Once the modal is shown, I want to create a checkout session which will require the id of the item being referred to in the modal. I am stuck at how to get the id.
  75. Here is the script for showing the modal and prepopulating it:
  76. let modal = document.getElementById(&quot;modal&quot;);
  77. modal.style.display = &quot;none&quot;;
  78. function modalHandler(val, content_id) {
  79. if (val) {
  80. let xhr = new XMLHttpRequest();
  81. xhr.onreadystatechange = function () {
  82. if (this.readyState == 4 &amp;&amp; this.status == 200) {
  83. let data = JSON.parse(this.responseText);
  84. document.getElementById(&quot;subtotal&quot;).innerHTML = data.subtotal;
  85. document.getElementById(&quot;taxes&quot;).innerHTML = data.taxes;
  86. document.getElementById(&quot;website_fee&quot;).innerHTML = data.website_fee;
  87. document.getElementById(&quot;total&quot;).innerHTML = data.total;
  88. fadeIn(modal);
  89. }
  90. };
  91. xhr.open(&quot;GET&quot;, &quot;/modal-content/&quot; + content_id + &quot;/&quot;, true);
  92. xhr.send();
  93. } else {
  94. fadeOut(modal);
  95. }
  96. }
  97. Here is the views.py which returns the JSON data:
  98. def modal_content_view(request, content_id):
  99. my_model = get_object_or_404(MyModels, content_id=content_id)
  100. print(f&quot;the model is {my_model.username}&quot;)
  101. data = {
  102. &#39;subtotal&#39;: my_model.username,
  103. &#39;taxes&#39;: &#39;2.60&#39;,
  104. &#39;website_fee&#39;: &#39;0.87&#39;,
  105. &#39;total&#39;: &#39;23.47&#39;,
  106. &#39;content_id&#39;:my_model.content_id
  107. }
  108. return JsonResponse(data)
  109. Here is the script that is supposed to fetch the data when the checkout button is clicked:
  110. &lt;script type=&quot;text/javascript&quot;&gt;
  111. var checkoutButton = document.getElementById(&#39;checkout-button&#39;);
  112. checkoutButton.addEventListener(&#39;click&#39;, function() {
  113. fetch(&quot;{% url &#39;checkout&#39; content_id %}&quot;, {
  114. method: &#39;POST&#39;,
  115. data: JSON.stringify({
  116. amount: &quot;{{ cost }}&quot; * 100,
  117. description: &quot;{{ title }}&quot;,
  118. gig_id: &quot;{{ gig_id }}&quot;,
  119. }),
  120. })
  121. .then(function(response) {
  122. return response.json();
  123. })
  124. .then(function(session) {
  125. return stripe.redirectToCheckout({ sessionId: session.id });
  126. })
  127. .then(function(result) {
  128. if (result.error) {
  129. alert(result.error.message);
  130. }
  131. })
  132. .catch(function(error) {
  133. console.error(&#39;Error:&#39;, error);
  134. });
  135. });
  136. &lt;/script&gt;
  137. Here is the view that handles the content_id passed from the script above:
  138. @csrf_exempt
  139. def create_checkout_session(request, content_id):
  140. model = MyModels.objects.get(content_id=content_id)
  141. subscription = Subscription(model=model, is_subscribed=False, user=request.user)
  142. And here is the onclick function that triggers the modal to show:
  143. onclick=&quot;modalHandler(true, &#39;{{content.model.content_id}}&#39;)&quot;
  144. My question is how do I pass the &#39;content_id&#39; from the modal to the script that handles checkout
  145. </details>
  146. # 答案1
  147. **得分**: 0
  148. Here is the translated code part without the content you mentioned:
  149. ```javascript
  150. checkoutButton.addEventListener('click', function() {
  151. console.log("Button clicked");
  152. fetch("{% url 'checkout' model.content_id %}", {
  153. method: 'POST',
  154. data: JSON.stringify({
  155. amount: "{{ cost }}" * 100,
  156. description: "{{ title }}",
  157. gig_id: "{{ gig_id }}",
  158. }),
  159. })
  160. .then(function(response) {
  161. return response.json();
  162. })
  163. .then(function(session) {
  164. return stripe.redirectToCheckout({ sessionId: session.id });
  165. })
  166. .then(function(result) {
  167. if (result.error) {
  168. alert(result.error.message);
  169. }
  170. })
  171. .catch(function(error) {
  172. console.error('Error:', error);
  173. });
  174. });
英文:

Although it is not working as I wanted, I found a temporary solution to this. I soled the issue by placing the javascript inside the for loop where I want to get the content_id of the item. Here is how the script not looks

  1. checkoutButton.addEventListener(&#39;click&#39;, function() {
  2. console.log(&quot;Button clicked&quot;)
  3. fetch(&quot;{% url &#39;checkout&#39; model.content_id %}&quot;, {
  4. method: &#39;POST&#39;,
  5. data: JSON.stringify({
  6. amount: &quot;{{ cost }}&quot; * 100,
  7. description: &quot;{{ title }}&quot;,
  8. gig_id: &quot;{{ gig_id }}&quot;,
  9. }),
  10. })
  11. .then(function(response) {
  12. return response.json();
  13. })
  14. .then(function(session) {
  15. return stripe.redirectToCheckout({ sessionId: session.id });
  16. })
  17. .then(function(result) {
  18. if (result.error) {
  19. alert(result.error.message);
  20. }
  21. })
  22. .catch(function(error) {
  23. console.error(&#39;Error:&#39;, error);
  24. });
  25. });

huangapple
  • 本文由 发表于 2023年4月11日 02:58:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定