Python 如何通过 AJAX 调用使用 jQuery 呈现 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22598334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:15:26  来源:igfitidea点击:

How to render HTML with jQuery from an AJAX call

javascriptjquerypythonhtmlajax

提问by Matthew Moisen

I have a select box with a list of books. The user can select a book and hit the submit button to view the chapters on a separate page.

我有一个带有书籍列表的选择框。用户可以选择一本书并点击提交按钮以在单独的页面上查看章节。

However, when the user changes the select box, I would like a partial page refresh to display the past notes the user entered on the book, and allow the user to write a new note for that book. I do not want the review and creation of notes for a particular book done on the next page with the chapters, as it will clutter it up.

但是,当用户更改选择框时,我希望部分页面刷新以显示用户在书中输入的过去笔记,并允许用户为该书编写新笔记。我不希望在带有章节的下一页上完成特定书籍的评论和创建注释,因为它会使它变得混乱。

I'm using Python/Bottle on the backend and its SimpleTemplate engine for the front end.

我在后端使用 Python/Bottle,在前端使用 SimpleTemplate 引擎。

Currently, when the select box is changed, an ajax call receives a Json string containing the book information and all the notes. This json string is then converted into a json object via jQuery.parseJson().

Currently, when the select box is changed, an ajax call receives a Json string containing the book information and all the notes. 这个 json 字符串然后通过jQuery.parseJson().

What I would like to be able to do is then loop over the notes and render a table with several cells and rows.

我希望能够做的是循环笔记并渲染一个包含多个单元格和行的表格。

Would I have to do this in jQuery/js (instead of bottle/template framework) ? I assume so as I only want a partial refresh, not a full one.

我是否必须在 jQuery/js(而不是瓶子/模板框架)中执行此操作?我假设是这样,因为我只想要部分刷新,而不是完整刷新。

I'm looking for a piece of code which can render a table with variable numbers of rows via jQuery/js from a json object that was retrieved with ajax.

我正在寻找一段代码,该代码可以通过 jQuery/js 从使用 ajax 检索的 json 对象呈现具有可变行数的表。

<head>
    <title>Book Notes Application - Subjects</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>

    <script>
        $(document).ready(function(){
            $('#subject_id').change(function(){
                var subject_id = $(this).val();
                $.ajax({
                    url : "subject_ajax?subject_id=" + subject_id,
                    success : function(data) {
                        alert(data)

                        json = jQuery.parseJSON(data);
                    },
                    error : function() {
                        alert("Error");
                    }
                });
            })
        })

    </script>
</head>
<body>

    <!-- CHOOSE SUBJECT -->
    <FORM action="/books" id="choose_subject" name="choose_subject" method="POST">
        Choose a Subject:
        <select name="subject_id" id="subject_id">
            % for subject in subjects:
                <option value="{{subject.id}}">{{subject.name}}</option>
            % end
        </select><input type="submit" name="sub" value="Choose Subject"/>
        <BR />
    </FORM>

采纳答案by John S

I'm not familiar with Python/Bottle or its SimpleTemplate engine, but you could consider generating the html for the table on the server side and returning it in the ajax response, rather than returning JSON.

我不熟悉 Python/Bottle 或其 SimpleTemplate 引擎,但您可以考虑在服务器端为表生成 html 并在 ajax 响应中返回它,而不是返回 JSON。

var subject_id = $(this).val();
$.ajax('subject_ajax', {
    type: 'get',
    data: { subject_id: subject_id },
    dataType: 'html',
    success : function(html) {
        // Insert the html into the page here using ".html(html)"
        // or a similar method.
    },
    error: function() {
        alert("Error");
    }
});

When calling .ajax():

打电话时.ajax()

  1. The "type" setting defaults to "get", but I prefer to explicitly set it.
  2. Use the "data" setting for the ajax call to specify the URL parameter.
  3. Always specify the "dataType" setting.
  1. “类型”设置默认为“获取”,但我更喜欢明确设置它。
  2. 使用 ajax 调用的“数据”设置来指定 URL 参数。
  3. 始终指定“dataType”设置。


I also recommend you perform the ajax call in an on-submit handler for the form, and add an on-change handler for the select that submits the form.

我还建议您在表单的 on-submit 处理程序中执行 ajax 调用,并为提交表单的 select 添加一个 on-change 处理程序。

$(document).ready(function(){
    $('#subject_id').change(function() {
        $(this.form).submit();
    });

    $('#choose_subject').submit(function(event) {
        event.preventDefault();
        var subject_id = $('#subject_id').val();
        if (subject_id) {
            $.ajax(...);
        }
    });
});

This way your submit button should work in case it is clicked.

这样你的提交按钮应该可以工作,以防它被点击。

回答by eje211

This greatly depends on how your JSON and HTML are formatted. But with a table somewhere like:

这在很大程度上取决于您的 JSON 和 HTML 的格式。但是在某处有一张桌子:

<table id="books">
  <tr>
    <th>Chapter</th>
    <th>Summary</th>
  </tr>
</table>

You could do something like:

你可以这样做:

$(function(){
    $('#choose_subject').submit(function () {
        var subject_id = $(this).val();
        $.getJSON("subject_ajax?subject_id=" + subject_id, function(data) {
            console.log(data);
            $.each(data.chapters, function (index, chapter) {
                $('#books').append('<tr><td>' + chapter.title + '</td><td>' + chapter.summary + '</td></tr>');
            })
        });
        return false;
    })
})

This supposes JSON like:

这假设 JSON 如下:

{
  "notes": [
    "Note 1",
    "Note 2"
  ],
  "chapters": [
    {
      "title": "First chapter",
      "summary": "Some content"
    },
    {
      "title": "Second chapter",
      "summary": "More content"
    }
  ]
}

Other notes:

其他注意事项:

  • If you use HTML 4 or earlier, keep all your tags in upper case. If you're using XHTML or HTML5, keep all your tags in lower case.
  • You don't need $(document).ready(function () {...}), with recent versions of jQuery $(function () {...} )works the same and it's easier to read.
  • You can use $.getinstead of $.jsonif you're only using the success state (as you are here). And if you're confident that the data you'll get is valid JSON, you can use getJSONinstead of get. It will parse the JSON for you deliver it to you as a JavaScript object automatically.
  • It's usually more convenient to use console.lograther than alertwhen you're testing. Actually, it's usually a bad idea in general to ever use alert.
  • 如果您使用 HTML 4 或更早版本,请将所有标签保持为大写。如果您使用 XHTML 或 HTML5,请将所有标签保持为小写。
  • 您不需要$(document).ready(function () {...}),最新版本的 jQuery$(function () {...} )工作方式相同,而且更易于阅读。
  • 如果您只使用成功状态(就像您在这里)$.get$.json则可以使用而不是。如果你有信心,你会得到的数据是有效的JSON,你可以使用getJSON的替代get。它将解析 JSON 以自动将其作为 JavaScript 对象交付给您。
  • 通常使用起来console.logalert在测试时更方便。实际上,通常使用alert.

回答by David Yerrington

There are a few things you need to look at:

您需要注意以下几点:

1) Is your SimpleTemplate library included? 2) Have you compiled your template via compileTemplate()?

1) 您的 SimpleTemplate 库是否包括在内?2) 你有没有通过 compileTemplate() 编译你的模板?

Once you know your library is included (check console for errors), pass your data returned to your success handler method, compile your template, that update whichever element you are trying to update.

一旦你知道你的库被包含(检查控制台是否有错误),将你返回的数据传递给你的成功处理程序方法,编译你的模板,更新你试图更新的任何元素。

I'm not sure that you want to update the same element that you're defining your template in.

我不确定您是否要更新在其中定义模板的相同元素。

$(document).ready(function(){
    $('#subject_id').change(function(){
        var subject_id = $(this).val();
        $.ajax({
            url : "subject_ajax?subject_id=" + subject_id,
            success : function(data) {

                var template_data = JSON.parse(data);
                var template = $('#subject_id').toString(); // reference to your template
                var precompiledTemplate = compileTemplate(template);
                var result = precompiledTemplate(template_data);
                $('#subject_id').append(result);

            },
            error : function() {
                alert("Error");
            }
        });
    })
})

You might also try moving your template out of the element you're trying to update like this:

您也可以尝试将模板移出您尝试更新的元素,如下所示:

<script type="text/template" id="subject-select-template">
% for subject in subjects:
    <option value="{{subject.id}}">{{subject.name}}</option>
% end
</script>

Then just create a blank select element like so:

然后像这样创建一个空白的选择元素:

<select id="select_id"></select>

Update references. Anyway, hope this is helpful. It should work but I can't test without your specific code ;)

更新参考。无论如何,希望这会有所帮助。它应该可以工作,但如果没有您的特定代码,我将无法进行测试;)

Also, check out this demo example if you haven't yet: https://rawgithub.com/snoguchi/simple-template.js/master/test/test.html

另外,如果您还没有,请查看此演示示例:https: //rawgithub.com/snoguchi/simple-template.js/master/test/test.html