繁体   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