Send a javascript variable to django view

隐身守侯 提交于 2021-01-23 06:50:07

问题


I am fetching the current url of the browser (which keeps changing) in a javascript variable (say var_url). I have a django model Url. I want to create its object using a view function create_url().

Earlier When I used a form, I used request.POST['field']. Now I don't have a form and I want to pass the value of var_url. How can that be done?

This was my view function when I was using a form:

def create_url(request):
if request.method == 'POST':
    text=request.POST['field']
    url_result=Url.objects.get_or_create(
        url_text=text
        )
    return HttpResponse('Url Object Created')

And the following was my form:

<form name='urlForm' method="post" action="{% url 'create_url'%}" id="create" >
        {% csrf_token %}
        <input type="text" id="myurl" name="field"/>
        <input type="submit" name="submit" value="Submit">
    </form>

Now rather than a form, I have this:

<div id='results'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
    window.addEventListener('message',function(e){
        results.innerHTML = e.data;
    });
</script>

I want to send the content of div tag to my view function.


回答1:


You have two way - using form and using ajax for sending data.

Assume that you have data called result_data in js.

First, use existing form

In this way, you have to update your inner data to form field (i.e. make hidden result_data field to send form data).

<form name='urlForm' method="post" action="{% url 'create_url'%}" id="create" >
    {% csrf_token %}
    <input type="text" id="myurl" name="field"/>
    <input type="hidden" name="result_data" value="" id="js_data_input">
    <input type="submit" name="submit" value="Submit">
</form> 

Then you add javascript code to add your result_data to your hidden input value. Maybe like this.. (I'm not good at javascript, so make it your own way)

<script>
    $('#js_data_input').val(result_data)
</script>

Then just submit your form with this data.

Second, use ajax

If you send your data without submit form (it means that not reload/escape current page), you can use ajax.

When using ajax, you have to make other view that receive your ajax request.

If you don't know about ajax, please check w3school or other web site.

This is example for send result_data using ajax

  $.ajax({
    type: "POST",
    url: '/your/path/to/ajax_view/url/',
    data: {
      'result_data': result_data,
      'csrfmiddlewaretoken': '{{ csrf_token }}'
    },
    dataType: "json",
    success: function(response) {
      if (response.result == 'ok') {
        alert(response.message);
      } else {
        alert('Failed');
      }
    }
  })

You have to add csrfmiddlewaretoken. Else, you got 403 forbidden error. You can make csrfmiddlewaretoken by js or just using {{ csrf_token }} from django.



来源:https://stackoverflow.com/questions/50851210/send-a-javascript-variable-to-django-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!