【问题标题】:Unordered Lists seen as undefined in HTML无序列表在 HTML 中被视为未定义
【发布时间】:2015-10-08 13:28:17
【问题描述】:

我正在尝试使用 AJAX 构建 REST API。 我的 C# 代码如下所示。

using System;
using System.Collections.Generic;
using System.Linq; 
using System.Net;
using System.Net.Http;
using System.Web.Http; 
using WebApplication2.Models;
using System.IO;
using System.Globalization;

namespace WebApplication2.Controllers
{
public class DefaultController : ApiController
{
    List<Default>players = new List<Default>();
    string path = Path.Combine(Directory.GetCurrentDirectory(), "\\players.txt");

    public IHttpActionResult GetAllPlayers()
    {
        String line;
        StreamReader file = new StreamReader(path);
        string[] data;
        while ((line = file.ReadLine()) != null)
        {
            data = line.Split(',');
            Default player = new Default(data[0],data[1],data[2],data[3],DateTime.ParseExact(data[4],
                "yyyy-mm-dd", CultureInfo.InvariantCulture));
            players.Add(player);
        }
        file.Close();
        return Ok (players); 
    }

我的 HTML 页面代码如下所示

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
</head>
<body>
  <div>
     <h2> All Players</h2>
       <ul id="players"/>

  </div>

  <div>
    <br />
    <h2> Search or Delete </h2>
    <select name="options_for_search_delete">
        <option value="id">ID</option>
        <option value="name">Name</option>
    </select>
    <input type = "text" id="data" size="5"/>
    <input type = "button" value="Search" onclick = "search()" />
    <input type = "button" value="Delete" onclick = "find()" />
    <br />
    <p id="players"/>

  </div>

  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
  <script>

    var uri = 'api/default';
    $(document).ready(function () {
        $.getJSON(uri).done(function(data){
              //success:function(data){
                $.each(data,function(key,item){
                    $('<li>',{text:format(item)}).appendTo($('#players'));

                });
            });
    });

    function format(item){
        return item.reg + "," + item.first + " " + item.last + "," + item.team;
    }

   </script>
 </body>
</html>

当我访问 api/default 页面时,输出符合预期。但是,当我访问 player.html 时,无序列表显示为未定义。我不知道如何解决这个问题。

【问题讨论】:

  • ID 在文档中必须是唯一的。您目前使用 ID players 两次。
  • 我将

    id = "players" 更改为 result_players。即使这样,问题仍然存在。

标签: c# html ajax api rest


【解决方案1】:

试试

<ul id="players"></ul> 

因为它是一个块元素,所以元素的 id 应该是唯一的。

【讨论】:

  • 我按照您的建议更改了我的 HTML 页面代码。但这没有帮助。
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
  • 2017-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多