前提
Djangoにて、ajax通信を用いてform内容を非同期でPOSTする機能を実装中。
実装は無事できまして、formに入力した内容を問題なくデータベースに登録することができました。
しかし、formを入力するページ内にiframe要素を入れると、ajax通信が機能しなくなる。
現状ではiframe要素には、ただ別のサイトを表示させているだけでそれ以外のことは何も行っておらず、iframe要素が同じページに存在しているだけで、ajax通信が機能しなくなってしまう原因がわからず苦戦しております。
プログラミング初心者です、基本的な内容で恐縮ですがご教授いただけますと幸いです。
実現したいこと
iframe要素が同ページ内にあっても非同期でPOSTできる様に実装したい。
何故iframe要素があるとajax通信が上手くいかないのかを理解したい。
発生している問題・エラーメッセージ
エラーは発生しませんが、Django内のファイルviews.pyでif request.is_ajax(): がfalseだと、formの内容をSAVEせずに、renderする様にしているので、renderされてします。
該当のソースコード
python:views.py
from .forms import CommentCreateForm from .models import Comment from django.http import JsonResponse def photo_add_view(request): form = CommentCreateForm(request.POST or None) data = {} if request.is_ajax(): #←iframe要素が同ページ内にあると、ここがfalseになってしまう。iframe要素がなければ問題なく実装できております。 if form.is_valid(): form.save() data['title']= form.cleaned_data.get('title') data['status']= 'ok' return JsonResponse(data) context = { 'form': form, } return render(request, 'building/main.html', context) 以下、当該機能と関係ないため省略 ・・・・・
HTML:base.html
{% load static %} <!doctype html> <html lang="ja"> <head> <title>モデルビューアー</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> </head> <body> <div class='container mt-3'></div> {% block content %} {% endblock %} <!-- Optional JavaScript --> <script type="text/javascript" src="{% static 'javascript/comment.js' %}"></script> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script> </body> </html>
HTML:main.html
{% extends 'building/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class='mt-3'> <div id='alert-box'></div> <form id='p-form' autocomplete="off"> {% csrf_token %} {{form|crispy}} <button type='submit' class='btn btn-primary'>Send</button> </form> <div> <iframe id="viewer" title="viewer" width="100px" height="100px" src="適当なURL"> </div> </div> {% endblock %}
Javascript:comment.js
const alertBox = document.getElementById('alert-box'); const form = document.getElementById('p-form'); const title = document.getElementById('id_title'); const text = document.getElementById('id_text'); const cordinate = document.getElementById('id_cordinate'); const csrf = document.getElementsByName('csrfmiddlewaretoken'); const url = ''; const handleAlerts = (type,text) => { alertBox.innerHTML = `<div class="alert alert-${type}" role="alert"> ${text} </div>` } form.addEventListener('submit',e=>{ e.preventDefault() const fd = new FormData(); fd.append('csrfmiddlewaretoken', csrf[0].value); fd.append('title', title.value); fd.append('text', text.value); fd.append('cordinate', cordinate.value); $.ajax({ type: 'POST', enctype: 'multipart/form-data', data: fd, success: function(response){ console.log(response); const sText = `succeccfully saved ${response.title}` handleAlerts('success', sText) setTimeout(()=>{ alertBox.innerHTML='' title.value = '' text.value = '' cordinate.value = '' },2000) }, error: function(error){ handleAlerts('danger', 'upps..somthing went wrong') }, cache: false, contentType: false, processData: false, }) });
試したこと
①CSRF関連の原因かと思い、調べてみたのですがそれっぽい情報を取得することができませんでした。
②iframeで表示しているサイト側の問題の可能性について。現状は自分自身がゲームエンジンで作成した物(静的なサイト)を表示していますが、iframe内のsrcを空にして、iframe要素のみを残した場合でも同様の現象が起こってしまった。
補足情報(FW/ツールのバージョンなど)
Django 3.2.7
Python 3.9.7
プログラミング初心者でして、基本的な内容で申し訳ありませんがご教授いただけますと幸いです。
まだ回答がついていません
会員登録して回答してみよう