为什么我不能将URL作为传递给ajax的data属性的json元素发送

时间:2015-02-23 06:55:35

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

我有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();
}

3 个答案:

答案 0 :(得分:2)

不需要对数据进行字符串化,你应该像以下一样以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
        });

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您的data: JSON.stringify(myData)应为data:myData,您不应stringifyPOST AJAX requests数据应有效 {{1} }。

object myData {@ 1}}

也是一个拼写错误