我正在尝试获取HTML代码的标签标记文本,但我无法获得它。
在以前的工作中,我从文本框中获取数据,但是现在我无法获取标签文本
html文件
<label name="hello_text">HELLO</label>
<input type="text" name="textbox1"/>
view.py文件
if request.method == "POST":
textbox = request.POST["textbox1"]
val = request.POST["hello_text"] #didn't get the value of label here
我要接收标签的文本值
答案 0 :(得分:0)
更新以使所有功能正常工作
***UPDATE to make everything work***
IN example.html above your js file include a token this will be used to authenticate with csrf using ajax
<script type="text/javascript">
var token = `{{ csrf_token }}`
</script>
In your .js file
$.ajax({
headers: {"X-CSRFToken": token}, //new item added here the csrf token
url: `${window.location.origin}/example/`, //url changed to be dynamic for all base origins
type: "POST",
data: JSON.stringify(param),
success: function () {
alert("Success");
},
error: function(error) {
console.log("error: " + error);
}
});
}
In your views.py
from django.http import HttpResponse
Class exampleView(TemplateView):
def post(self, request):
body = json.loads(request.body.decode('utf-8')) # I was incorrect in assuming how to parse body params
value = body['value']
label = body['label']
return HttpResponse('')
---------------------------------- 结束更新 < / strong> ----------------------------------
这是使用jquery的示例
在example.html
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script src="{% static 'js/example.js' %}" type="text/javascript"></script>
<label id="label1" name="hello_text">HELLO</label>
<input type="text" id="input1" name="textbox1"/>
<button id="submit-btn>submit form</button>
在example.js
//when document is loaded
$(document).ready(function() {
//create an event listener for a button by id = submit-btn
$('#submit-btn').click(function() {
// call a function called submit form.
submitForm();
});
})
function submitForm() {
//use jquery id selector to get the text of the label
// use jquery id selector to get the value attr of an input
let label = ('#label-1').text();
let value = ('#input-1').attr('value');
// build an object( dictonary) of items sent to post request
var param = {
"value" : value,
"label" : label,
}
// create an ajax request to submit the form this will call the django view
// it knows its a post because type == POST
// data must be turned to json to pass back to view
// on success a function will alert a message and redirect to a new page
$.ajax({
url: `http://127.0.0.1/example`,
type: "POST",
data: JSON.stringify(param),
success: function () {
alert("Success");
window.load('http://127.0.0.1/home')
},
error: function(error) {
console.log("error: " + error);
}
});
}
然后您认为
value = request.POST.get("value", "")
label = request.POST.get("label", "")