我正在javascript函数中进行典型的ajax调用:
$.ajax({
type: 'GET',
url: '@Url.Content("~/Incident/LookUpStudent")',
data: { userInput: userInputStudentLDN },
success: function (result) { //doing stuff here}
});
此调用转到控制器中的此方法:
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错误,即使是新的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
我现在不知道为什么这会增加"行动"到网址的末尾.. 为什么这会导致404错误,我该如何解决?
根据Kosala W回答编辑1
var req = { userInput: userInputStudentLDN };
$.get('@Url.Content("~/Incident/LookUpStudent")', { userInput: req }, function (result) {
//result is your response from the controller
});
答案 0 :(得分:1)
像这样改变你的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
});
如下所示更改您的控制器。
[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);
}
}
答案 1 :(得分:0)
尝试在其中添加type
:
$.ajax({
type: 'GET',
url: '@Url.Content("~/Incident/LookUpStudent")',
data: { term: document.getElementById("Term").value, classNum: document.getElementById("ClassNumber").value},
success: function (result) { //doing stuff here}
});
答案 2 :(得分:0)
令人尴尬的是,这个问题是由@ Html.BeginForm('Action','Incident')中的<button>
引起的。
按钮默认提交表单(即使我没有明确设置type =“submit”) 与此同时,我还在按钮的点击事件上运行javascript的Ajax语句。
因此,ajax调用以及一个名为“Action”的不存在的操作结果的帖子。
感谢所有试图提供帮助的人!