【问题标题】:ASP.NET Core / jQuery - Uncaught TypeError when trying to display a JSON [duplicate]ASP.NET Core / jQuery - 尝试显示 JSON 时未捕获的 TypeError [重复]
【发布时间】:2018-11-07 11:32:08
【问题描述】:

我有一个 TCP 侦听器,它正在侦听包含酒店 ID 和名称的传入 JSON 字符串,一旦收到 JSON,我想显示一个酒店列表及其名称作为列表。但是,在 chrome 控制台中,我收到以下错误:

jquery.js:489 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in "[{\"Id\":1,\"Name\":\"Hotel Ritz\"},{\"Id\":2,\"Name\":\"Scandic\"},{\"Id\":3,\"Name\":\"Hotel Villa Provence\"},{\"Id\":4,\"Name\":\"First Hotel Atlantic\"}]"
at isArrayLike (jquery.js:489)
at Function.each (jquery.js:351)
at Object.success (site.js?v=5BUCGd0L7FqRV9EDqjbCXfE3SLPjEtoSfd2jy5c48yU:26)
at fire (jquery.js:3268)
at Object.fireWith [as resolveWith] (jquery.js:3398)
at done (jquery.js:9305)
at XMLHttpRequest.<anonymous> (jquery.js:9548)

site.js:

const uri = "/api/hotel";

let hotels = null;

$(document).ready(function () {

getData();

});

function getData() {
$.ajax({
    type: "GET",
    url: uri,
    cache: false,
    success: function (data) {
        const tBody = $('#hotels');

        $(tBody).empty();

        $.each(data, function (key, item) {
            const tr = $("<ul></ul>")
                .append($("<li></li>").text(item.name));

            tr.appendTo(tBody);
        });

        hotels = data;
    }
});
}

HotelController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VIABooking.Models;

namespace VIABooking.Controllers
{
[Route("/api/hotel")]
[ApiController]
public class HotelController : ControllerBase
{
    //private readonly DatabaseContext _context;
    private readonly ModelManager modelManager = new ModelManager();

    /*[HttpGet]
    public ActionResult<List<Hotel>> GetAll()
    {      
        return _context.HotelItems.ToList();
    }*/

    [HttpGet]
    public ActionResult<string> GetAll()
    {
        return modelManager.GetHotelList(); 
    }

}
}

家庭控制器:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using VIABooking.Models;

namespace VIABooking.Controllers
{
public class HomeController : Controller
{

    private readonly ModelManager modelManager = new ModelManager();

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Hotel()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
}

ModelManager.cs:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;sing System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace VIABooking.Models
{
public class ModelManager : IModelManager
{
    private readonly TcpConnectionManager tcpManager = new TcpConnectionManager();

    public ModelManager() {}

    public string GetHotelList ()
    {
        return tcpManager.GetHotelList();
    }
}
}

TCPListener.cs:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters.Json;

namespace VIABooking.Models
{
public class TcpConnectionManager
{        
    public string GetHotelList()
    {
        //Sending json to other server

        const int PORT_NO = 5005;
        const string SERVER_IP = "127.0.0.1";

        TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
        NetworkStream ns = client.GetStream();

        string s = "Please send me a list of all hotels!";

        string json = JsonConvert.SerializeObject(s);

        byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(json);

        ns.Write(bytesToSend, 0, bytesToSend.Length);


        //Receiving json from other server

        byte[] buffer = new byte[client.ReceiveBufferSize];

        int bytesRead = ns.Read(buffer, 0, client.ReceiveBufferSize);

        string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead);

        string json2 = JsonConvert.SerializeObject(dataReceived);

        client.Close();
        ns.Close();

        return json2;
    }
}
}

【问题讨论】:

    标签: javascript c# jquery asp.net-core


    【解决方案1】:

    您可以使用以下选项之一来解决您的问题:

    • 客户端const hotels = JSON.parse(data)获取js-object 而不是字符串
    • $.ajax的设置参数中添加dataType: json
    • 返回List&lt;Hotel&gt;JsonResult,而不是服务器端api/hotels 中的字符串。它会将响应的 Content-type 更改为 application/json,因此 jquery 将自动解析 json

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多