簡體   English   中英

Javascript:使用 Ajax 發送 JSON 對象?

[英]Javascript : Send JSON Object with Ajax?

這可能嗎?

xmlHttp.send({
    "test" : "1",
    "test2" : "2",
});

也許有: content typeapplication/json的標題?:

xmlHttp.setRequestHeader('Content-Type', 'application/json')

否則我可以使用:

xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

然后JSON.stringify JSON 對象並將其作為參數發送,但如果可能的話,以這種方式發送它會很酷。

使用 jQuery:

$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });

沒有 jQuery:

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({name:"John Rambo", time:"2pm"}));

如果您不使用 jQuery,請確保:

var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);

而對於 php 接收端:

 $_POST['json_name'] 

我掙扎了幾天才找到任何對我有用的東西,就像傳遞多個 id 數組並返回一個 blob 一樣。 事實證明,如果使用 .NET CORE 我使用的是 2.1,您需要使用 [FromBody] 並且只能使用一次,您需要創建一個視圖模型來保存數據。

總結如下內容,

var params = {
            "IDs": IDs,
            "ID2s": IDs2,
            "id": 1
        };

就我而言,我已經對數組進行了 json 處理並將結果傳遞給函數

var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());

然后調用 XMLHttpRequest POST 並將對象字符串化

var ajax = new XMLHttpRequest();
ajax.open("POST", '@Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");           
ajax.onreadystatechange = function () {
    if (this.readyState == 4) {
       var blob = new Blob([this.response], { type: "application/octet-stream" });
       saveAs(blob, "filename.zip");
    }
};

ajax.send(JSON.stringify(params));

然后有一個這樣的模型

public class MyModel
{
    public int[] IDs { get; set; }
    public int[] ID2s { get; set; }
    public int id { get; set; }
}

然后通過 Action 像

public async Task<IActionResult> MyAction([FromBody] MyModel model)

如果您返回文件,請使用此附加組件

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>

在解決問題的 json 周圍添加Json.stringfy

暫無
暫無

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

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