【问题标题】:Update div html and content with ajax使用 ajax 更新 div html 和内容
【发布时间】:2011-02-24 11:04:32
【问题描述】:
我希望你有一个类似于 Stack Overflow 网站左上角的 StackExchange 链接的功能。
据我了解,点击堆栈交换链接后,会发生以下情况:
我注意到 html 和数据没有出现在页面标记中,所以我认为它可能是使用 javascript/jquery/ajax 获取的。
注意 - 我正在使用 asp.net mvc 2 和 linq-to-sql。
请举例说明如何实现这一点,或者提供类似示例的链接,
谢谢。
【问题讨论】:
标签:
javascript
jquery
ajax
linq-to-sql
asp.net-mvc-2
【解决方案1】:
您可以在后面的代码中使用 jQuery 和页面方法来实现这一点。
//Gets the list of requests
function getRequestList() {
// call server-side webmethod using jQuery
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Index.aspx/GetOrdersForApproving",
data: "{ }", // send an empty object for calls with no parameters
dataType: "json",
success: displayRequests,
failure: reportError
});
}
//displays the requests in the ul
function displayRequests(result) {
// ASP.NET encapsulates JSON responses in a property "d"
if (result.hasOwnProperty("d")) { result = result.d; }
// iterate through player list and add info to the markup
var ul = $("#requestsForApproval");
for (i = 0; i < result.length; i++) {
var li = $("<li class='approvalListItem'><div>"
+ "<h3>" + result[i].OrderID + " - " + result[i].Supplier + "</h3>"
+ "</div>"
+ "<div>"
+ result[i].Description
+ "</div>"
+ "<div> "
+ "<table width='100%'>"
+ "<tr>"
+ "<td>"
+ "Quant: " + result[i].Quantity
+ "</td>"
+ "<td>"
+ "Price: " + result[i].UnitPrice
+ "</td>"
+ "<td>"
+ "Total: " + result[i].Value
+ "</td>"
+ "</tr>"
+ "</table>"
+ "</div>"
+ " <div class='approvalButtons' style='display:none'>"
+ "<ul><li class='approveButton'>Approve</li>"
+ "<li class='rejectButton'>Reject</li></ul>"
+ "</div>"
+ "<input type='hidden' class='hiddenID' name='OrderLineID' value='" + result[i].OrderLineID + "'>"
+ "</li>");
ul.append(li);
}
代码背后:
/// <summary>
/// Gets a list of Request Lines
/// </summary>
/// <returns>List of order lines</returns>
[WebMethod]
public static List<iOrderLine> GetOrdersForApproving()
{
try
{
List<iOrderLine> Lines = new List<iOrderLine>();
foreach (Objects.Database.OrderLine oOrderLine in Objects.Database.OrderLine.GetLinesWaitingFor(StaticStore.CurrentUser.UserID, int.MinValue))
{
Lines.Add(new iOrderLine(oOrderLine));
}
return Lines;
}
catch (Exception)
{
throw;
}