javascript - 使用 Controller 中的 WebClient.DownloadString(url) 时,Ajax 调用上出现 HTTP 404

标签 javascript c# json ajax asp.net-mvc

我正在 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/

相关文章:

c# 将进度条添加到文本框

ajax - 使用 cakephp 的简单 json 响应

json - 在 Golang 中完全解析时间戳

javascript - 为什么 uploadcare 每 N 毫秒重绘 html 标签?

javascript - NodeJs 压力测试工具/方法

c# - 合并列表列表中的交叉项

c# - 将 C++ 数组移植到 C# 数组

javascript - Json 对象推送无法使用 AngularJS

javascript - 如何根据 ajax 调用的成功或错误返回表单的 "onsubmit"属性的 bool 值?

javascript - OrbitControls 和 dat.gui 文本不起作用