简体   繁体   English

如何使用Ajax在JavaScript中获取MVC Controller json数据

[英]How to get MVC Controller json data in JavaScript using ajax

I am using .NET C# MVC/API project. 我正在使用.NET C#MVC / API项目。 Inside a Controller I have the following code: 控制器内部,我有以下代码:

    [HttpGet]
    public ActionResult ArcGISinit()
    {
        var jsonString = "[{ 'number': '555', 'api': '777', 'text': 'text'}]";
        return Json(jsonString, JsonRequestBehavior.AllowGet);
    }

Then in my script file, I am able to get the above data like this: 然后,在我的脚本文件中,我可以像这样获得以上数据:

        // Path to the above **Controller**
        var serviceURL = "...";

        var respOriginal = [{ "number": 555, "api": "777", "text": text }]; 

        $.ajax({
            type:        "GET",
            url:         serviceURL,
            contentType: "application/json;",
            dataType:    "json",
            success:     successFunc,
            error:       errorFunc
        });

        function successFunc(data, status) {

            // Probably don't need this
            resp = JSON.stringify(data); 

            console.log("data:");
            console.log(data);
            console.log("respOriginal:");
            console.log(respOriginal);
        }

        function errorFunc() {
            alert('MVC controller call failed.');
        }

Here is a thing when I look at it Chrome debugger, in data which is from MVC Controller I get this (a plain string): 当我看它Chrome调试器时,这是一件事情,在MVC Controller的 数据中 ,我得到了这个(纯字符串):

[{ 'number': '555', 'api': '777', 'text': 'text'}]

but for respOriginal which is inside a script file, I get this 但是对于脚本文件中的respOriginal ,我得到了

[Object]

When Object is expanded (data in respOriginal ) looks properly formatted, like so: 展开对象时( respOriginal中的数据)看起来格式正确,如下所示:

number : 555
api : 777
text : "text"

How can I make data that comes from MVC Controller look like data in respOriginal ? 我如何可以使来自MVC控制器 的数据看起来像respOriginal数据?

I would suggest creating WebAPI controller for API functions, it is more flexible out of the box and made just. 我建议为API函数创建WebAPI控制器,它开箱即用且更加灵活。 Also you are separating your API from your views, and can have 401 or error handling just by changing the HttpStatusCode parm 另外,您还从视图中分离API,仅通过更改HttpStatusCode参数就可以进行401或错误处理

[HttpGet]
public async Task<HttpResponseMessage> ArcGISinit()
{
    var yourObjectArray = new object[] { new { number = 555, api = 777, text = "text" } };
    return Request.CreateResponse(HttpStatusCode.OK, yourObjectArray);
}

And for the JS you are right you don't need stringfy (that is when you want to cast JS object to JSON formated string), just use the variable like data.number 对于JS,您是对的,您不需要stringfy(也就是说,当您要将JS对象转换为JSON格式的字符串时),只需使用data.number之类的变量即可。

Make an anonymous object or pass in any instance of a class resembling your structure ... you got square brackets around the object so i guess it's an array: 制作一个匿名对象或传递类似于您的结构的类的任何实例...在对象周围有方括号,因此我想它是一个数组:

[HttpGet]
public ActionResult ArcGISinit()
{
    object[] yourObjectArray = new object[]{ new { number = 555, api = 777, text = "text"} };
    return Json(yourObjectArray , JsonRequestBehavior.AllowGet);
}

A proper class would look like: 适当的类如下所示:

public class YourClass
{
    public int number {get;set;}
    public int api {get;set;}
    public string text {get;set;}
}

And on the controller: 并在控制器上:

[HttpGet]
public ActionResult ArcGISinit()
{
    YourClass[] yourClassArray = new Yourclass[]{ new Yourclass { number = 555, api = 777, text = "text"} };
    return Json(yourClassArray , JsonRequestBehavior.AllowGet);
}

Would work the same way if you'd use a List<YourClass> 如果您使用List <YourClass>,将以相同的方式工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM