Javascript:使用 Ajax 发送 JSON 对象?

IT技术 javascript ajax json header request
2021-02-06 09:11:30

这可能吗?

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

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

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

否则我可以使用:

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

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

4个回答

使用 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"}));
好吧,如果您的帖子正文应该是 JSON 例如 ({name:"John",time:"2pm"}) 使用内容类型 application/json 如果您的帖子正文是表单 urlencoded 数据 (name=John&time=2pm) 使用 application/ x-www-form-urlencoded
2021-03-27 09:11:30
但是我也可以使用 content-type:application/x-www-form-urlencoded如果我使用 stringify,那么使用的意义application/json何在?:)
2021-04-01 09:11:30
我应该把网址放在哪里?
2021-04-04 09:11:30
@CIRK:有什么关系?内容类型设置是完全任意的,除非服务器特别对待其中一个。这只是在一天结束时来回流动的数据。
2021-04-06 09:11:30
@ShuruiLiu URL 代替方法"/json-handler"的第二个参数open()
2021-04-10 09:11:30

如果您不使用 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'] 
亲爱的朋友,你能把这个 POST ajax 与页面上使用的全部需要的代码分享一下吗?或者,如果你有一个使用 JSON 的 vanilla ajax POST 的完整工作示例的链接,也谢谢你
2021-03-14 09:11:30
这并不是真正发送 JSON,而是发送表单数据。也可以直接发送JSON,这种情况下不能用$_POST读取,而是用json_decode(file_get_contents('php://input'));
2021-03-19 09:11:30
不能直接使用吗?
2021-03-25 09:11:30
我认为这不能回答所提出的问题。我相信开发人员希望将 JSON 的 blob 作为 Content-Type: application/json 发送到 PHP,而不是包装在 urlencoded 包装器中。
2021-04-09 09:11:30

我挣扎了几天才找到任何对我有用的东西,就像传递多个 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.stringfy解决问题的 json