html:
{% extends 'base.html' %}
{% block content %}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create a Recipe</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'title' : $('input[name=T]').val(),
'tags' : $('select[name=tags]').val(),
'ingredients' : $('select[name=ingredients]').val(),
'time_minutes' : $('input[name=Time]').val(),
'price' : $('input[name=P]').val(),
'link' : $('input[name=link]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '/api/recipe/recipes/', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
</head>
<body class="">
<form method="POST">
{% csrf_token %}
<br>
<label for="T">Title: </label>
<input type="text" name="T" value="">
<br>
<label for="Ingr">Ingredients: </label>
<select multiple name="ingredients">
{% for ing in Ing %}
<option value="{{ing.pk}}">{{ing}}</option>
{%endfor%}
</select>
<br>
<label for="Tag">Tags: </label>
<select multiple name="tags">
{% for tag in Tag %}
<option value="{{tag.pk}}">{{tag}}</option>
{%endfor%}
</select>
<br>
<label for="Time">Time: </label>
<input type="text" name="Time" value="">
<br>
<label for="P">Price: </label>
<input type="text" name="P" value="">
<br>
<label for="link">Link: </label>
<input type="text" name="link" value="">
<br>
<input type="submit" name="submit" value="Post">
</form>
</body>
</html>
{%endblock%}
这是我的 HTML 我将此表单发布到我的其余 API 中,除了数组/选择发布为 null/0 之外,所有表单都发布了,这里是发布/数据控制台的内容:
id: 57 成分: Array(0)
长度:0
原型:数组(0)
链接:“recipe.com”
价格:“3.00”
标签:数组(0)
长度:0
原型:数组(0)
time_minutes:20
title: "oOao"
原型:对象
如您所见,即使我选择了一个选项,作为数组的成分和标签也不会发布。
答案 0 :(得分:0)
我通过创建一个 toString 变量解决了这个问题:
var tags = $('select[name=tags]').val();
var tagsS = tags.toString();
var ingredients = $('select[name=ingredients]').val();
var ingredientsS = ingredients.toString();
var formData = {
...
'tags' : tagsS,
'ingredients' : ingredientsS,
...
};
感谢您的帮助