【发布时间】:2017-03-15 22:43:01
【问题描述】:
我整天都在为此苦苦思索。似乎没有任何工作。这是我的情况。
我有一个包含两个字段的 Django 表单:redirect_from、redirect_to。此表单有两个提交按钮:Validate 和 Save。当页面加载时,Submit 被隐藏,只显示Validate。
所以现在,当用户填写两个字段并单击Validate 时,我使用 Ajax 来确认两个字段相同。如果是,请显示Save 按钮。单击Save 按钮应将表单保存到数据库中。我还添加了一个oninput 监听器,这样在进行Ajax 调用之后,如果用户尝试更改数据,Save 按钮就会再次隐藏,他现在必须再次评估它。
显然,这对于 Ajax 来说应该很容易,但我发现它非常困难和令人沮丧。到目前为止,这是我的代码:
我的模板:
form method="post">
{% csrf_token %}
{% include 'partials/form_field.html' with field=form.redirect_from %}
{% include 'partials/form_field.html' with field=form.redirect_to %}
<button id="submit" class="btn btn-lg btn-primary" type="submit" name="save" value="Save">Save</button>
<button id="ajax_submit" class="btn btn-lg btn-primary" type="submit" name="ajax" value="Ajax">Validate</button>
</form>
{% endblock %}
{% block extra_scripts %}
{{ block.super }}
<script type="text/javascript">
$(document).ready(function() {
$("#submit").hide()
});
$('#id_redirect_to').on('input', function(){
$("#submit").hide()
});
console.log("hello")
//For getting CSRF token
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
//For doing AJAX post
//When submit is click
$("#ajax_submit").click(function(e) {
console.log("Clicked")
e.preventDefault();
//Prepare csrf token
var csrftoken = getCookie('csrftoken');
//Collect data from fields
/*var email = $('#inputEmail').val();*/
var redirect_from= $('#id_redirect_from').val();
var redirect_to= $('#id_redirect_to').val();
console.log("URL from and to is", redirect_from, redirect_to)
/*var password = $('#inputPassword').val();*/
//Send data
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
data : { csrfmiddlewaretoken : csrftoken,
redirect_from : redirect_from,
redirect_to : redirect_to
/*password : password*/
}, // data sent with the post request
// handle a successful response
success : function(json) {
console.log(json); // another sanity check
//On success show the data posted to server as a message
if (json['redirect_success'] === 'true')
{
alert("They are the same!" +json['redirect_success'] +'!.' );
$("#submit").show()
}
else
{
$("#submit").hide() //Maybe display some error message in the future!
}
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
});
</script>
{% endblock extra_scripts %}
我的观点:
def edit_redirect(request, pk):
if request.method == 'GET':
red_url = MarketingRedirect.objects.get(pk=pk)
data = {'redirect_from': red_url.redirect_from, 'redirect_to': red_url.redirect_to}
form = RedirectEditForm(initial=data)
return render (request, 'marketing_redirect/edit_redirect.html', {'form': form,
'redirect_from': red_url.redirect_from})
if request.POST['save'] == 'Save':
form = RedirectEditForm(request.POST)
if form.is_valid():
red_url = MarketingRedirect.objects.get(pk=pk)
data = form.cleaned_data
red_url.redirect_from = data['redirect_from']
red_url.redirect_to = data['redirect_to']
red_url.save()
return redirect('backend_redirect')
if request.POST['ajax'] == 'Ajax':
if request.is_ajax():
redirect_from = request.POST.get('redirect_from')
redirect_to = request.POST.get('redirect_to')
if redirect_from == redirect_to:
data = {'redirect_success': 'true'}
return JsonResponse(data)
else:
data = {'redirect_success': 'false'}
return JsonResponse(data)
我收到了500: MultiValueDictKeyError at "'Save'"
有人可以在这里指导我正确的方向吗?对 ajax 很陌生。
【问题讨论】:
标签: javascript jquery python ajax django