【问题标题】:Javascript : Send JSON Object with Ajax?Javascript:使用 Ajax 发送 JSON 对象?
【发布时间】:2011-09-19 01:55: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 对象并在参数中发送它,但如果可能的话,以这种方式发送它会很酷。

【问题讨论】:

    标签: javascript ajax json header request


    【解决方案1】:

    使用 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"}));
    

    【讨论】:

    • 但是如果我使用 stringify,我也可以使用 content-type:application/x-www-form-urlencoded,那么使用 application/json 有什么意义呢? :)
    • @CIRK:有什么关系?内容类型设置是完全任意的,除非服务器特别对待其中之一。这只是一天结束时来回流动的数据。
    • 好吧,如果您的帖子正文应该是 JSON,例如 ({name:"John",time:"2pm"}) 如果您的帖子正文是表单 urlencoded 数据(名称=John&time=2pm) 使用 application/x-www-form-urlencoded
    • 我应该把网址放在哪里?
    • @ShuruiLiu URL 代替"/json-handler" 作为open() 方法的第二个参数
    【解决方案2】:

    如果您不使用 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'] 
    

    【讨论】:

    • 不能直接用吗?
    • 我认为这不能回答所提出的问题。我相信开发人员希望将 JSON 的 blob 作为 Content-Type: application/json 发送到 PHP,而不是包装在 urlencoded 包装器中。
    • 这并不是真正发送 JSON,而是发送 formdata。也可以直接发送 JSON,这种情况下不能用 $_POST 读取,而是用 json_decode(file_get_contents('php://input'));
    • 亲爱的朋友,你能把这个 POST ajax 与页面上使用的全部代码分享吗?或者,如果您有一个带有 JSON 的 vanilla ajax POST 的完整工作示例的链接,也谢谢您
    【解决方案3】:

    我苦苦挣扎了几天才找到对我有用的方法,比如传递多个 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>
    

    【讨论】:

      【解决方案4】:

      在解决问题的 json 周围添加 Json.stringfy

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-14
        • 2016-10-21
        • 2016-11-11
        • 1970-01-01
        • 2020-11-28
        • 1970-01-01
        相关资源
        最近更新 更多