【问题标题】:Why I can not send URL as json element which is passed to the data attribute of ajax为什么我不能将 URL 作为传递给 ajax 数据属性的 json 元素发送
【发布时间】:2015-02-23 17:32:50
【问题描述】:

我有 ajax 请求,我将数据传递给 data 属性,如下所示:

var myData = { "Identifier": 12312312, 
               "Description": "description",
               "Name": "name", 
               "ImageUlr": "http://icons.iconarchive.com/icons/rob-sanders/hat/256/Hat-baseball-red-icon.png", 
               "Price": "price" };

$.support.cors = true;


$.ajax({ type: 'POST',
         dataType: 'json',
         url: myUrl + categoryId,
         data: JSON.stringify(myData),
         contentType: 'application/json',
         success: function (returnedData) {},
         error: function (xhr, ajaxOptions, thrownError) {},
         processData: false,
         async: false
       });

当它到达服务器(Web Api)时,ImageUrl 为空。这是我的服务器端:

public IHttpActionResult PostProduct ([FromBody] Product postedProduct, string categoryId)
{
   this.dbManager.PushNewProductInCategory(postedProduct, categoryId);
   return Ok();
}

【问题讨论】:

    标签: jquery ajax json asp.net-web-api


    【解决方案1】:

    不需要对数据进行字符串化,你应该像下面这样以 json 格式发送它,这样就可以了。

    var myData = { "Identifier": 12312312, "Description": "description", "Name": "name", "ImageUrl": "http://icons.iconarchive.com/icons/rob-sanders/hat/256/Hat-baseball-red-icon.png", "Price": "price" };
    

    $.support.cors = true;

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: myUrl + categoryId,
                data: myData,
                contentType: 'application/json',
                success: function (returnedData) {},
                error: function (xhr, ajaxOptions, thrownError) {},
                processData: false,
                async: false
            });
    

    【讨论】:

      【解决方案2】:

      好吧,我不能 100% 确定这会解决您的问题,您确实有一个错字“ImageUlr”

      【讨论】:

        【解决方案3】:

        您的data: JSON.stringify(myData) 应该是data:myData,而不是stringify,因为POST AJAX requests 中的数据应该是有效 object

        他们在myData 中的拼写错误ImgUlr 应该是ImgUrl

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-12
          • 1970-01-01
          • 2022-07-28
          • 1970-01-01
          • 1970-01-01
          • 2012-01-06
          相关资源
          最近更新 更多