这可能吗?
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对象发送到参数中,但是如果可能的话,以这种方式发送它会很酷。
使用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; }
}
然后像
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
本文地址:http://javascript.askforanswer.com/javascriptshiyongajaxfasongjsonduixiang.html
文章标签:ajax , header , javascript , json , request
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
文章标签:ajax , header , javascript , json , request
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!