我一整天都在为这事犯愁。似乎什么都没用。这是我的情况。在
我有一个Django表单,有两个字段:redirect_from,redirect_to。此表单有两个提交按钮:Validate和{}。当页面加载时,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 %}
Save
Validate
{% endblock %}
{% block extra_scripts %}
{{ block.super }}
$(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
}
});
});
{% endblock extra_scripts %}
我的观点:
^{pr2}$
我得到了500: MultiValueDictKeyError at "'Save'"
有人能把我引向正确的方向吗?对ajax很陌生。在