簡體   English   中英

jQuery.ajax GET不結束參數

[英]Jquery.ajax GET not ending parameters

我正在為公司Intranet上的內容生產區域創建UI。 我在上一個項目中創建了中間件API。 這是我第一次使用RESTful方法(而且我對Javascript和jquery還是比較陌生的)

當我從jquery.ajax調用調試本地api時,JSON對象未在我的GET方法上正確傳遞。

在C#API中

[ActionName("THING")]
        [HttpGet()]
        public string GetThing(object json)
        {
            GetData getData;
            if (json == null)
                return null;
            else if (json is string && (json as string).StartsWith("{"))
                getData = JsonConvert.DeserializeObject<GetData>(json as string);
            else
                return null; 
            ItemReturn retVAl = new ItemReturn();

[logic to use JSON]

return retVal;

在網頁中

loadThings: function (thingNumber, showBool) {
                showBool = (showBool === true);
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    data: '{ "GetData" : {"ThingNumber":"' + thingNumber + '","Show": ' + showBool + '}}',
                    url: "http://localhost:11422/api/THING/THING/GetThing",
                    contentType: "application/json; charset=utf-8",

                    success: function (result) {

[logic to display things]

}

我可以在GetThing中擊中我的breakPoint,一切正常,但是我似乎無法弄清楚為什么我的重載中的對象(json)為空。 我知道這是javascript中的東西,我的單元測試可以正常工作,而我的JavaScript正在將我帶到方法的斷點,我只需要重載JSON對象即可實際傳遞

UPDATE

它在api端。 我將GetThing的重載從(對象json)更改為([FromUri()]對象json)。 這解決了當前的問題,但是當前它只是將JSON對象轉換為空白對象

++注意:我必須將post方法重載更改為[FromBody()]而不是[FromUri()],但我尚未更新DELETE方法以查看使用哪種方法

您是否可以嘗試添加Ajax設置: traditional:true, ,?

所以問題1,您無法使用GET進行此操作。 兩種選擇

  1. 使用POST
  2. 字符串化並使用GET

1)這就是您使用POST的方式

修復您的ajax請求,如下所示:

$.ajax({
  type: "POST",
  dataType: "json",
  data: { "GetData" : {"ThingNumber": thingNumber ,"Show": showBool }}, // JS object not string
  url: "http://localhost:11422/api/THING/THING/GetThing",
  contentType: "application/json; charset=utf-8",

請閱讀$.ajax發布文檔以獲取有關說明https://api.jquery.com/jquery.post/

2)使用GET

var obj = JSON.stringify({ "GetData" : {"ThingNumber": thingNumber ,"Show": showBool }}),
    url = "http://localhost:11422/api/THING/THING/GetThing?json=" + encodeURIComponent(obj);

$.ajax({
      type: "GET",
      dataType: "json",
      url: url, // Here we encode the obj for server
      contentType: "application/json; charset=utf-8",

如果使用此方法,則必須更改控制器以將json參數作為String獲取,然后使用選擇的庫將其解析為JSON。 如何使用C#解析JSON?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM