Javascript:使用 Ajax 发送 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6418220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:39:13  来源:igfitidea点击:

Javascript : Send JSON Object with Ajax?

javascriptajaxjsonheaderrequest

提问by Adam

Is this possible?

这可能吗?

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

Maybe with: a header with content type: application/json?:

可能带有:带有content type: application/json?:

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

Otherwise I can use:

否则我可以使用:

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

and then JSON.stringifythe JSON object and send it in a parameter, but it would be cool to send it in this way if it's possible.

然后JSON.stringify是 JSON 对象并将其作为参数发送,但如果可能的话,以这种方式发送它会很酷。

回答by Nathan Romano

With jQuery:

使用 jQuery:

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

Without jQuery:

没有 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"}));

回答by shantanu chandra

If you`re not using jQuery then please make sure:

如果您不使用 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);

And for the php receiving end:

而对于 php 接收端:

 $_POST['json_name'] 

回答by Dave

I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.

我挣扎了几天才找到任何对我有用的东西,就像传递多个 id 数组并返回一个 blob 一样。事实证明,如果使用 .NET CORE 我使用的是 2.1,您需要使用 [FromBody] 并且只能使用一次,您需要创建一个视图模型来保存数据。

Wrap up content like below,

总结如下内容,

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

In my case I had already json'd the arrays and passed the result to the function

就我而言,我已经对数组进行了 json 处理并将结果传递给函数

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

Then call the XMLHttpRequest POST and stringify the object

然后调用 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));

Then have a model like this

然后有一个这样的模型

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

Then pass in Action like

然后通过 Action 像

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

Use this add-on if your returning a file

如果您返回文件,请使用此附加组件

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

回答by user3310115

Adding Json.stringfyaround the json that fixed the issue

添加Json.stringfy解决问题的 json