我試圖查詢數據庫,並在我的網頁中得到結果,但它必須通過JavaScript(Ajax,jQuery)來完成。我搜索了幾個小時,沒有任何工作。它要麼拋出解析器錯誤,說SyntaxError: Unexpected end of input
,或者只是未定義出來。從JsonResult返回一個字符串數組,並在JavaScript中使用它
我使用以下JsonResult方法:
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
public JsonResult NextArticle(int slideID)
{
var articles = db.Slides.ToList();
var currentArticle = db.Slides.First(s => s.SlideId == slideID);
int articlePosition = articles.IndexOf(currentArticle);
articlePosition = (articlePosition + 1) >= articles.Count() ? 0 : articlePosition + 1;
var nextArticle = articles.ElementAt(articlePosition);
//nextArticle.Article.ArticleText.Substring(0, 50)+"..."
string[] returnParameters = {
nextArticle.SlideId.ToString(),
nextArticle.Image.ImageURL,
nextArticle.Article.ArticleTitle,
nextArticle.Article.ArticleText
};
return Json(returnParameters);
}
而下面的JavaScript函數:
function nextSlide() {
var articleLink = document.getElementsByTagName("a")[0];
$.ajax({
type: 'POST',
url: "../SlideShow/NextArticle",
data: {
slideID: articleLink.getAttribute("id"),
},
dataType: 'json', //Some places are saying I should leave this out
success: function (result) {
$(articleLink).id = result[0];
document.getElementById("articleImage").setAttribute("src", result[1]);
document.getElementById("articleTitle").innerHTML = result[2];
document.getElementById("articleText").innerHTML = result[3];
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
}
貴控制器正確地獲取數據。 –
嘗試把contentType:「application/json; charset = utf-8」, – AmmarCSE
@AmmarCSE我在dataType中添加了'contentType:「application/json; charset = utf-8」,''dataType:'json','仍然拋出解析器錯誤。我也試過把'dataType:'json','out,但它不影響它 – Shadow