这是我的功能:问题是我不知道如何将“价值”添加到“链接”。
function add_subject_to_subjects_list() {
var value = $("#id_name").val();
var link = "/subject/create/"+value;
show_subjects_list();
$("#btn-create-subject").click(function() {
$.post(link, function(data) {
show_subjects_list();
alert(data).hide("fast");
});
});
}
因此,我的函数将数据发布到不同的链接:http://127.0.0.1:8000/subject/create/
但我希望我的链接取决于价值:它应该看起来像:
http://127.0.0.1:8000/subject/create/some_value/
这就是该页面的整个 js:
$(document).ready(function (){
add_subject_to_subjects_list();
});
function show_subjects_list() {
$.post("/subject/list/", function(data){
for( var i=0; i<data.length; i++) {
$("#list").append('<li>'+data[i]['fields']['name']+'</li><br>');
};
}, 'json');
}
function add_subject_to_subjects_list() {
var value = $("#id_name").val();
var link = "/subject/create/"+value;
show_subjects_list();
$("#btn-create-subject").click(function() {
$.post(link, function(data) {
show_subjects_list();
alert(data).hide("fast");
});
});
}
那是我的服务器端(我正在使用 Django/Python):
@csrf_exempt
def subjects_list(request):
user = request.user
subjects = Subjects.objects.filter(user__exact = user)
result = serializers.serialize("json", subjects, fields=('name'))
return HttpResponse(result)
@csrf_exempt
def new_subject(request, subject):
subject, created= Subjects.objects.get_or_create(
name=subject,
user=request.user,
created_by=request.user)
if created:
message = "Subject was created"
else:
message = "No subject was added to the database"
return HttpResponse(message)
那是我的html:
{% block left-menu %}
<div class="sidebar">
<h3>Subjects</h3>
<p> Enter subject name to add </p>
<br>
<div id="create-subject">
<form method="post" action="."> {% csrf_token %}
{{ subject_creation_form.as_p }}
<input type="button" value="Create Subject" id="btn-create-subject" />
</form>
</div>
<div id="subjects-list">
<a id="append">myID</a>
<ul id="list">
</ul>
</div>
</div>
{% endblock %}
那是那个html的形式:
class SubjectCreationForm(forms.Form):
name = forms.CharField(label="Subject Name", widget=forms.TextInput(attrs={'size':9}))
class Meta:
exclude = ('created_by', 'created_time', 'num_of_followers', 'vote')
def clean_name(self):
name = self.cleaned_data['name']
if len(name)>1:
return name
else:
raise forms.ValidationError("Subject name should be longer")