使用ajax向DJango传递多个参数的全部代码包含html,以及使用js向DJango传递多个参数的全部代码包含html
时间: 2023-12-29 19:06:09 浏览: 89
使用Ajax向Django传递多个参数的全部代码包含HTML:
HTML代码:
```html
<form id="my-form">
<input type="text" name="param1" value="">
<input type="text" name="param2" value="">
<button type="button" onclick="submitForm()">submit</button>
</form>
<div id="result"></div>
```
JavaScript代码:
```javascript
function submitForm() {
var form_data = {
'param1': $('input[name=param1]').val(),
'param2': $('input[name=param2]').val()
};
$.ajax({
url: '/your_django_view/',
type: 'POST',
data: form_data,
success: function(data) {
$('#result').html(data);
}
});
}
```
Django视图函数:
```python
from django.http import JsonResponse
def your_django_view(request):
if request.method == 'POST':
param1 = request.POST.get('param1')
param2 = request.POST.get('param2')
# process the parameters here
response_data = {'result': 'success'}
return JsonResponse(response_data)
else:
return JsonResponse({'error': 'Invalid request method'})
```
使用JS向Django传递多个参数的全部代码包含HTML:
HTML代码:
```html
<form id="my-form">
<input type="text" name="param1" value="">
<input type="text" name="param2" value="">
<button type="button" onclick="submitForm()">submit</button>
</form>
<div id="result"></div>
```
JavaScript代码:
```javascript
function submitForm() {
var form_data = new FormData();
form_data.append('param1', $('input[name=param1]').val());
form_data.append('param2', $('input[name=param2]').val());
$.ajax({
url: '/your_django_view/',
type: 'POST',
processData: false,
contentType: false,
data: form_data,
success: function(data) {
$('#result').html(data);
}
});
}
```
Django视图函数:
```python
from django.http import JsonResponse
def your_django_view(request):
if request.method == 'POST':
param1 = request.POST.get('param1')
param2 = request.POST.get('param2')
# process the parameters here
response_data = {'result': 'success'}
return JsonResponse(response_data)
else:
return JsonResponse({'error': 'Invalid request method'})
```
注意:使用FormData时需要将processData和contentType设置为false,否则数据会被处理为默认的Content-Type格式。
阅读全文