我正在 javascript 函数中进行典型的 ajax 调用:
$.ajax({
type: 'GET',
url: '@Url.Content("~/Incident/LookUpStudent")',
data: { userInput: userInputStudentLDN },
success: function (result) { //doing stuff here}
});
此调用转到 Controller 中的此方法:
public string LookUpStudent(string userInput)
{
if (string.IsNullOrWhiteSpace(userInput)) { return "Student not found. Please try again."; }
try
{
var fetchedData = new WebClient().DownloadString(JSONUrl); //download the data from the URL
}
//return statement and other stuff here
}
我简化了 LookUpStudent 方法,但基本上,当我逐步执行代码并到达我调用的这部分时
new WebClient().DownloadString(JSONUrl);
我的当前页面立即收到 404 错误,即使 new WebClient().DownloadString(JSONUrl);调用成功。 fetchedData 只是允许我在从 ajax 方法返回字符串之前进行一些验证。
这是 404 错误:
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Incident/Action
我现在不明白为什么这会将“Action”添加到网址末尾。 为什么这会导致 404 错误以及如何解决此问题?
根据 Kosala W 答案编辑 1:
var req = { userInput: userInputStudentLDN };
$.get('@Url.Content("~/Incident/LookUpStudent")', { userInput: req }, function (result) {
//result is your response from the controller
});
最佳答案
像这样改变你的jquery。
var req = { term: document.getElementById("Term").value, classNum: document.getElementById("ClassNumber").value };
$.get("/Incident/LookUpStudent", { userInput: req }, function (result) {
//result is your response from the controller
});
如下所示更改您的 Controller 。
[HttpGet]
public JsonResult LookUpStudent(object userInput)
{
try
{
if (userInput == null)
{
throw new Exception("Student not found. Please try again.");
}
var fetchedData = new WebClient().DownloadString(JSONUrl); //download the data from the URL
return Json(fetchedData, JsonRequestBehavior.AllowGet);
}catch(Exception ex)
{
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
}
关于javascript - 使用 Controller 中的 WebClient.DownloadString(url) 时,Ajax 调用上出现 HTTP 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34143432/