[英]why isn't jscript displaying my items?
我有以下Javascript:
$(document).ready(function () {
$.getJSON("api/products/",
function (data) {
$.each(data, function (key, val) {
// Format the text to display.
var str = val.Name + ': $' + val.Price;
// Add a list item for the product.
$('<li/>', { text: str })
.appendTo($('#products'));
});
});
});
我的問題是產品列表沒有顯示。 我還有另一個功能,可以搜索列表中的單個項目,並且可以顯示這些項目,但是為什么這不起作用?
這是信息存儲在的類:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
這是控制器:
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public Product GetProductById(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return product;
}
public IEnumerable<Product> GetProductsByCategory(string category)
{
return products.Where(
(p) => string.Equals(p.Category, category,
StringComparison.OrdinalIgnoreCase));
}
}
我是ASP.NET的初學者,所以請讓我知道我做錯了什么。
我認為您打算將文本用作創建<li>節點的初始jQuery選擇器的一種方法。
將第二個參數傳遞給$()實際上將導致一個“上下文”,該上下文將嘗試限制選擇器的起始位置。 參見: http : //api.jquery.com/jQuery/#jQuery1/
$(function() {
var data = [{ Name: 'test1', Price: 1000}, { Name: 'test2', Price: 25}];
$.each(data, function (key, val) {
// Format the text to display.
var str = val.Name + ': $' + val.Price;
// Add a list item for the product.
$('<li/>')
.text(str)
.appendTo($('#products'));
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.