如何创建嵌套的ajax请求?

时间:2016-10-27 15:59:30

标签: javascript c# ajax asp.net-web-api

我有一个运行良好的WEB API。我想通过Ajax请求调用一个属于我的API的动作。它似乎很简单,我让它适用于简单的请求。但是,我试图放置嵌套调用,并且由于某种原因,传递给第二个请求的数据会丢失。我想知道这是一个范围问题还是我在代码中做错了。

以下是javascript代码:

$("#submit_request").click(function () {
        var firstName = $("#first_name").val();
        var lastName = $("#last_name").val();
        var faciltiy = $("#facility").val();

        // Collecting all the documents into an array of JSON
        var documents = [];

        var request = JSON.stringify({
            "PatientFirstName": firstName,
            "PatientLastName": lastName,
            "Facility": faciltiy
        });

        //the first request is working fine and it has a success state
        $.ajax({
            url: "http://localhost:64611/api/requests/createRequest",
            type: "POST",
            dataType: 'json',
            contentType: 'application/json',
            data: request,
            success: function (request_id, state) {


      for (var i = 0; i < 5; i++) {
         var RequestDocument = {
            "RequestID": i,
            "DocumentID": i+1,
            "StartDate": Date(),
            "EndDate": Date()
         };

         documents.push(RequestDocument);

      }
                console.log(documents); // it is returning a correct object
                console.log(typeof (documents)); // type object

                $.ajax({
                    url: "http://localhost:64611/api/requests/addDocumentsOfARequest/",
                    type: "post",
                    datatype: 'json',
                    contenttype: 'application/json',
                    data: JSON.stringify(documents), ---> this object should be passed to the api action
                    success: function (response, state) {

                    },
                    error: function (err) {
                        if (err) {

                        }
                    }
                });

            },
            error: function (err) {
                if (err) {

                }
            }
        });        
    });

我的api操作的定义类似于以下

public async Task<IHttpActionResult> addDocumentsOfARequest(RequestDocument[] documents) 

RequestDocument类如下所示:

public class RequestDocument
    {
        [Required]
        public int RequestID { get; set; }
        [Required]
        public int DocumentID { get; set; }
        [Required]
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }

我的WebApiConfig如下所示:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "defaultApiRoutes",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { id = @"\d+" }   // Only matches if "id" is one or more digits.
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        }
    }

参数&#39;文件&#39;是空的。有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

这是我的确切工作代码:

服务器

public class GamesController : ApiController
    {
        // GET api/<controller>
        [HttpPost]
        public async Task<IHttpActionResult> Post(RequestDocument[] document)
        {
            var req = await Request.Content.ReadAsStringAsync();
            return Ok();
        }
    }

public class RequestDocument
    {
        [Required]
        public int RequestID { get; set; }
        [Required]
        public int DocumentID { get; set; }
        [Required]
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }

的JavaScript

var documents = [];

    for (var i = 0; i < 5; i++) {
        var RequestDocument = {
            "RequestID": i,
            "DocumentID": i+1,
            "StartDate": Date(),
            "EndDate": Date()
        };

        documents.push(RequestDocument);

    }


    $.ajax({
        url: "http://localhost:1757/api/games",
        type: "POST",
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(documents),
        success: function(a, b) {
            alert("Done");
        }
    });

结果

enter image description here

答案 1 :(得分:0)

试试这个,

$.ajax({
    url: "http://localhost:1757/api/games",
    type: "POST",
    dataType: 'json',
    contentType: 'application/json',
    data: {
            document: documents
          },
    success: function(a, b) {
        alert("Done");
    }
});