javascript - jquery ajax contentType是啥意思?

查看:132
本文介绍了javascript - jquery ajax contentType是啥意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

POST请求contentType设置为application/json,但请求却把data的json转成了字符串?
请大神指教是什么原因?
代码如下

$.ajax({
        method: 'POST',
        url: "demo_test.txt",
        data: {
            aa: 1,
            bb: 2
        },
        contentType: "application/json",
        success: function (result) {}
    });

请求抓包

POST http://localhost:8888/demo_test.txt HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 9
Origin: localhost
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36
Content-Type: application/json
Accept: */*
X-Requested-With: XMLHttpRequest
Referer: http://172.17.35.112:8099/
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.8
Cookie: selectFluence=4; VFS_USERNAME=admin; VFS_PASSWORD=123456; VFS_APPURL=; VFS_ISSAVE=true; VFS_ISDMZ=true; webserver_is_save=0; _alert=1495876699555

aa=1&bb=2

这个问题已被关闭,原因:问题已解决 - 问题已解决,且对他人无借鉴意义

解决方案

参考:jQuery.ajax() 文档

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

Type: Boolean or String

When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

一般是用 application/x-www-form-urlencoded,也就是默认值,上传文件通常是用 multipart/form-data,现在很多使用 JSON 接口的也用后面这种。text/plain 我平时见得不多。

补充

jQuery 的 ajax 要发送 application/json 请求需要

  1. contentType: "application/json;charset=UTF-8"

  2. processData: false

  3. data: stringify(aObject)

比如

$.ajax("https://blablabla.com/", {
    contentType: "application/json;charset=UTF-8",
    dataType: "json",
    type: "post",
    processData: false,
    data: JSON.stringify({
        user: {
            name: "hello",
            pass: "world"
        },
        stamp: new Date()
    })
});

这篇关于javascript - jquery ajax contentType是啥意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆