使用 jquery ajax 提交 raw 文本,如 json、xml等

Javascript 2020-03-04 阅读 548 评论 0

使用 jquery 的 ajax,post 发送数据到服务端,请求头 Content-Type 默认是 application/x-www-form-urlencoded; charset=UTF-8,有时候我们需要提交 raw 文本,如 json、xml、html 等,就需要修改一下 ajax 参数的 headers 属性。

发送请求 raw 文本的 body,实际上是将整个数据的字符串格式放到 data 属性,同时需要设置 headers,指定相应的 http Content-Type,后端语言才能识别,不设置可能会有异常错误。

提交 json

json 的数据,使用 JSON.stringify转化为字符串。

var data = {
    username: "test",
    arr: [2, 3],
};
$.ajax({
    url: "/index.php",
    data: JSON.stringify(data),
    type: "post",
    headers: {
        "content-type": "text/plain; charset=utf-8" // 添加这一行
        //"content-type": "application/json; charset=utf-8" // 或者添加这一行
    },
    beforeSend: function (){
        console.log("提交中...");
    },
    error: function() {
        console.log("失败");
    },
    success: function (data){
        console.log(data);
    }
});

提交 xml

var data = '<xml><username>test</username></xml>';
$.ajax({
    url: "/index.php",
    data: data,
    type: "post",
    headers: {
        "content-type": "application/xml"   // 添加这一行
    },
    beforeSend: function (){
        console.log("提交中...");
    },
    error: function() {
        console.log("失败");
    },
    success: function (data){
        console.log(data);
    }
});
最后更新 2020-06-28