[英]how can i connect my form to ajax and post through it
我的 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>
<form class="" action="index.html" method="post">
<br>
<label for="T">Title: </label>
<input type="text" name="T" value="">
<br>
<label for="Ingr">Ingredients: </label>
<select class="" name="Ingr">
<option value=""></option>
</select>
<br>
<label for="Tag">Tags: </label>
<select class="" name="Tag">
<option value=""></option>
</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>
</form>
</head>
<body class="">
</body>
</html>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script>
var data = {
title: 'title',
tags: [],
ingredients: [],
time_minutes: 25,
price: 10.5
};
var headers = {'X-CSRFToken': '{{ csrf_token }}' }; // Inject our token into the javascript using a template tag
$.ajax({
type: 'POST',
data: data,
headers: headers, // Set the headers in the request
url: '/api/recipe/recipes/',
success: function(res){
console.log(res)
},
});
</script>
{%endblock%}
我想知道如何在 ajax 中访问我的表单我有 var 数据并且它正在发布但我希望从正文中的表单中获取数据我的意思是我希望用户从我的表单中放入他自己的数据一直在努力做到这一点提前谢谢你
您可以像这样获取输入的值:
var data = {
title: $('[name="T"]').val(),
tags: $('[name="Tag"]').val(),
ingredients: $('[name="Ingr"]').val(),
time_minutes: $('[name="Time"]').val(),
price: $('[name="P"]').val()
};
提交表单时,您将执行代码:
$('form').on('submit', function() { /* your code here */ });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.