<p>在AJAX成功块中,您必须告诉它您希望它如何处理这些信息:</p>
<pre><code>$(".next-step1").click(function (e) {
var form = $(this).closest("form");
var number1 = $("#CC").val();
var number2 = $("#PP").val();
$.ajax({
url: form.attr("data-validate-number-url"),
data: {
'number1': number1,
'number2':number2
},
dataType: 'json',
success: function (data) {
// 'data' is the dictionary received from the view.
// You could call it whatever you want.
$('#sum).html(data.sum_json);
/* Find 'id="sum"' and replace what's inside the tags(or innerHTML)
with the dictionary value of 'sum_json'.
If other keys exist in the 'data' dictionary,
they are accessed the same way, as in 'data.sum_json_2'.
*/
}
});
</code></pre>
<p>在索引.html在</p>
^{pr2}$
<p>视图</p>
^{3}$
<p>这是我们<code>render_to_string</code>发送给AJAX的模板。它呈现模板的方式与<code>render</code>相同。在</p>
<p>总和_模板.html在</p>
<pre><code>{{ sum }}
</code></pre>
<p>您不希望<code>render_to_string</code><code>index.html</code>,因为您在<code><p></code>中插入了整个<code>index</code>模板,而不仅仅是<code>sum</code>。您可能还想在视图中添加<code>if</code>语句</p>
<pre><code>if request.is_ajax() and request.POST:
</code></pre>
<p>过滤掉非AJAX请求。在</p>
<p>我听说有更好的方法。我只是自己想出来的,不知道是什么。如果你需要更多的细节请告诉我。在</p>