![](/img/trans.png)
[英]How can I print element of array from Flask on javascript on HTML
[英]How can I print data from database in flask app using javascript and react components?
我是 js 和 React 的新手。 我想使用 javascript 從 html 頁面中的數據庫中打印一些數據並做出反應。 我有一個簡單的 Flask 應用程序,它在數據庫中存儲了一些帶有可能答案的表單問題。 我想在我的 React 組件中動態打印它們。 有沒有辦法根據問題的數量在循環中創建組件? 這是我的 Python 代碼片段:
@app.route('/form.html')
def form():
form_data = db.get_all_questions()
return render_template("form.html", data=form_data)
這是我的表格。html:
<div class="questions">
<div class="question" id="question1">
</div>
<div class="question" id="question2">
</div>
<div class="question" id="question3">
</div>
</div>
這是我的js文件:
class Question extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<p>{this.props.content}</p>
<p>{this.props.id}</p>
<div className="rating_scale">
<form>
<label>
<input type="radio" name="rad" value="1" />
<span>1</span>
</label>
<label>
<input type="radio" name="rad" value="2" />
<span>2</span>
</label>
<label>
<input type="radio" name="rad" value="3" />
<span>3</span>
</label>
<label>
<input type="radio" name="rad" value="4" />
<span>4</span>
</label>
<label>
<input type="radio" name="rad" value="5" />
<span>5</span>
</label>
</form>
</div>
</div>
);
}
}
ReactDOM.render(
<Question content= "question 1" />,
document.querySelector("#question1")
);
ReactDOM.render(
<Question content= "question 2" />,
document.querySelector("#question2")
);
ReactDOM.render(
<Question content= "question 3" />,
document.querySelector("#question3")
);
在 HTML 我可以循環拋出我的問題,如下所示:
{% for question in data %}
<tr>
<td>{{ question['question_id'] }}</td>
<td>{{ question['question_text'] }}</td>
<br>
{% for AnswerId, Answer in question['possible_answers'].items()%}
<td> {{AnswerId}} : {{Answer}} </td>
<br>
{% endfor %}
</tr>
{% endfor %}
但是如何在 javascript 中獲得類似的行為? 我只是不想硬編碼我所有的問題 div,而是根據問題的數量創建動態包含此 div 的反應組件。 在內容道具中,我想顯示問題文本。
所以解決方案是我認為的最簡單的。 我只需鍵入以下內容即可訪問 html 中的數據:
{{data}}
所以我創建了div:
<div id="mydiv" data-questions='{{ data|tojson }}'></div>
在我的 javascript 文件變量中:
var guestions = JSON.parse(document.getElementById("mydiv").dataset.questions);
也許這不是最好的解決方案,但現在它工作正常。 現在我必須對元素進行 map 並為每個問題創建一個組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.