簡體   English   中英

使用 get 方法將數據從 ajax 發送到服務器

[英]Send data from ajax to server with get method

這個主題與其他主題不重復我的問題是在獲取方法中我有這些數據:

var things = [
   { "name": "n1" },
   { "name": "n2" }
];

Ajax 調用:

$.ajax({
    url: /controller/GetList,
    data: JSON.stringify(things),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

服務器端:

public JsonResult GetList(
    List<Thing> things) => Json("OK");

public class Thing
{
    public string name { get; set; }
}

現在,當我使用方法:“POST”調用 ajax 並在服務器端使用 [FromBody] 獲取數據時,一切正常,但如果我想使用 GET 方法調用 ajax,服務器端的東西是 Z37A6259CC0?6899A786,

我試試這個:

data: JSON.stringify({ things: things })
traditional: true

但它不起作用

我的項目在 Asp.net Core 3.1

您應該避免為GET請求發送數據(在請求正文中),因為它可能會帶來並發症。 許多服務,不要期望GET請求有一個主體,因此他們只是忽略它。

如果不是很多數據,您可以嘗試在查詢字符串中發送它,但我建議只使用POST

只需指定獲取方法:

$.ajax({
    type : "GET",
    url: /controller/GetList,
    data: JSON.stringify(things),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

如果您確實想發出GET HTTP 請求並在 JavaScript 客戶端上傳遞數據,您可以嘗試通過查詢字符串傳遞它們,如下所示。

var par = "";

$.each(things, function (i,val) {
    par += "&things[" + i + "].name=" + val.name;
});

$.ajax({
    url: "/controller/GetList?" + par.substring(1, par.length),
    //data: JSON.stringify(things),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

動作GetList

public JsonResult GetList([FromQuery]List<Thing> things) => Json("OK");

測試結果

在此處輸入圖像描述

暫無
暫無

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

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