【问题标题】:Issue with displaying the Jquery Ajax response in HTML在 HTML 中显示 Jquery Ajax 响应的问题
【发布时间】:2016-03-25 11:02:23
【问题描述】:

我需要加载一个页面,该页面需要显示一些具有动态分页的值。所以要加载值我有一个休息调用,在那个休息调用中我返回一个 json 对象。在浏览器控制台中,我可以看到 json 输出。现在我的问题是我得到了$document.ready() 函数的响应。现在我正在尝试在 HTML 中显示没有发生的 json 对象值。

JavaScript:

<script type="text/javascript">
$(document).ready(function(){
    $.ajax({ 
           url : "http://localhost:8080/school-service/school/list/students/1/1",
           type: "GET",
           dataType: "json",
          }).done( function(studentList) {
              console.log("AJAX request success:" +studentList.pageNumber);
            }).fail( function(jqXHR, textStatus) {
              console.log("AJAX request failed with status:" + textStatus);
          });
    });
</script>

HTML:

 <a href="#" class="next"><img onclick='previousPage("${studentList.pageNumber}", "${studentList.pageCount}")' src="${context}/images/previous.png"></a>


        <c:forEach var="i" begin="1" end="${studentList.pageCount}">
            <a href="${context}/school/list/students/1/${i}" id="${i}" class="pages">${i}</a>
         </c:forEach>

<a href="#" class="prev"><img onclick='nextPage("${studentList.pageNumber}", "${studentList.pageCount}")' src="${context}/images/next.png"/></a>

谁能帮我看看如何在 HTML 中显示 json 响应对象的值。

【问题讨论】:

  • console.log("AJAX request success:" +studentList.pageNumber); 有什么回报吗?
  • 是的,它正在返回“AJAX 请求成功:5”
  • 好的,您希望在 HTML 中显示响应对象值的位置。
  • 在for循环和标签中。在上面的代码中,我在哪里使用 ${studentList.pageNumber} 和 ${studentList.pageCount}。
  • 检查我的答案@Vinod。

标签: javascript jquery html json ajax


【解决方案1】:

我认为您不能,因为您要在页面中替换的代码属于服务器端语言(我猜是 asp),服务器端代码将在 javascript 执行之前编译,所以您不会找到了那些标签的标签。

【讨论】:

    【解决方案2】:

    所以,如果我理解您要做什么,您是在尝试从 AJAX 请求中获取值并将 .done 的返回值包含在 html 中?

    如果是这种情况,请查看此链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

    如果您从 .done 返回 JSON 对象,则需要将 JSON 对象解析为字符串,以便将其放入 DOM。从那时起,您将需要决定它应该放在哪里。例如,您可以创建一个 div 并说 $('that-div').append(returned value)。

    另一种方法可能是在 html 中设置默认值,然后在 .done 上,通过在响应中调用 .html 来替换 html。但要做到这一点,您需要获取 $(this) 的引用。

    我希望这会有所帮助,如果不让我知道我的差距在哪里,我们可以用不同的方式解决这个问题。

    【讨论】:

      【解决方案3】:

      你写的代码是带有JSTL的服务器端代码,在AJAX响应返回时不可用。

      1. JSP 页面将被转换为 HTML。
      2. HTML 页面将使用 AJAX 调用服务器。
      3. 返回的响应是在 Javascrip 对象中接收的 JSON。
      4. 你需要做一些 javascrip 工作来制作你的 a 标签

      您需要编写一些 Javascript 代码来呈现返回的响应。

      【讨论】:

        【解决方案4】:

        试试这个

        int pageCount = studentList.pageNumber;
        

        然后在您的 html 中简单地执行此操作

        <c:forEach var="i" begin="1" end=studentList.pageNumber>
                <a href="${context}/school/list/students/1/" + i id=i class="pages">i</a>
             </c:forEach>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-04-16
          • 1970-01-01
          • 1970-01-01
          • 2012-11-02
          • 2013-06-02
          • 2013-03-04
          • 1970-01-01
          相关资源
          最近更新 更多