簡體   English   中英

AJAX 或 Javascript POST 請求 Django 表單並獲取結果

[英]AJAX or Javascript POST request for Django form and get the result

我正在研究一個基於 django 的項目,在該項目中我集成了經過 ML 訓練的模型,以檢查 https url 是否合法。 for this I need javascript or ajax to call a rest api for my form in which I want to send a post request so that I can check if a https url is legitimate or not.

注意:我的代碼運行成功,並在 postman 上給出了正確答案。 所以只想將它與我的 HTML 表格集成

表格.html:

<form role="form" class="form" onsubmit="return false;">
        {% csrf_token %}
      <div class="form-group">
        <label for="data">SITE URL</label>
        <textarea id="data" class="form-control" rows="5"></textarea>
      </div>
      <button id="post" type="button" class="btn btn-primary">POST</button>
    </form>

    <div id="output" class="container"></div>

    <script src="/axios.min.js"></script>
    <script>
      (function () {
        var output = document.getElementById('output');
        document.getElementById('post').onclick = function () {
          var data = document.getElementById('data').value;

          axios.post('http://127.0.0.1:8000/predict/', JSON.parse(data))
            .then(function (res) {
              output.className = 'container';
              output.innerHTML = res.data;
            })
            .catch(function (err) {
              output.className = 'container text-danger';
              output.innerHTML = err.message;
            });
        };
      })();
    </script>

網址.py:

path('form/', form, name="form"),
path('predict/', predict, name='predict')

here predict/ URL is for my ML model to validate a https URL ML Model: I am returning this response:

if list(model.predict([test]))[0] == 1:
        return JsonResponse({"Response":"Legitimate"})
else:
    return JsonResponse({"Response":"Phishing or fake"})

下面我提供了一個示例,因為您只是在尋找可能的解決方案:

<form role="form" action="{% url 'predict' %}" class="form" 
    onsubmit="newPrediction(event, this)">
        {% csrf_token %}
      <div class="form-group">
        <label for="data">SITE URL</label>
        <textarea id="data" class="form-control" rows="5"></textarea>
      </div>
      <button id="post" type="button" class="btn btn-primary">POST</button>
</form>
    
<script>
function newPrediction(e, form) {
        e.preventDefault();

        const output = document.getElementById('output');
        const formData = new FormData(form);
    
        fetch(form.action, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(html => {
            output.innerHTML = html.Response
        });
      }
</script>

如果您還有其他問題,請發表評論,我將更新此答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM