这是我的功能: 问题是我不知道如何在“链接”中添加“值”。
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")
答案 0 :(得分:1)
单击处理程序附加在页面加载上并使用id_name
的值,我假设该时间为空,单击按钮时使用id_name
的值。
function add_subject_to_subjects_list() {
show_subjects_list();
$("#btn-create-subject").click(function() {
$.post("/subject/create/"+$("#id_name").val(), function(data) {
show_subjects_list();
alert(data);//.hide("fast");
});
});
}
同样对show_subjects_list
答案 1 :(得分:0)
......
$("#btn-create-subject").click(function() {
var value = $("#id_name").val();
var link = "/subject/create/"+value;
$.post(link, function(data) {
alert(data);
});
.......
感谢大家)