zoukankan      html  css  js  c++  java
  • What is content-type and datatype in an AJAX request?

    https://api.jquery.com/jquery.ajax/

    What is content-type and datatype in an AJAX request?

    contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.

    dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.

    If you're posting something like:

    {"name":"John Doe"}

    and expecting back:

    {"success":true}

    Then you should have:

    var data = {"name":"John Doe"}
    $.ajax({
        dataType : "json",
        contentType: "application/json; charset=utf-8",
        data : JSON.stringify(data),
        success : function(result) {
            alert(result.success); // result is an object which is created from the returned JSON
        },
    });

    If you're expecting the following:

    <div>SUCCESS!!!</div>

    Then you should do:

    var data = {"name":"John Doe"}
    $.ajax({
        dataType : "html",
        contentType: "application/json; charset=utf-8",
        data : JSON.stringify(data),
        success : function(result) {
            jQuery("#someContainer").html(result); // result is the HTML text
        },
    });

    One more - if you want to post:

    name=John&age=34

    Then don't stringify the data, and do:

    var data = {"name":"John", "age": 34}
    $.ajax({
        dataType : "html",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
        data : data,
        success : function(result) {
            jQuery("#someContainer").html(result); // result is the HTML text
        },
    });

    $.ajax - dataType

    • contentType is the header sent to the server, specifying a particular format.
      • Example: I'm sending json or XML
    • dataType is you telling jQuery what kind of response to expect.
      • Expecting JSON, or XML, or HTML, etc....the default it for jQuery to try and figure it out.

    The $.ajax() documentation has full descriptions of these as well.

    In your particular case, the first is asking for the response to be in utf-8, the second doesn't care. Also the first is treating the response as a javascript object, the second is going to treat it as a string.

    So the first would be:

    success: function(data) {
      //get data, e.g. data.title;
    }

    The second:

    success: function(data) {
      alert("Here's lots of data, just a string: " + data);
    }
  • 相关阅读:
    我的软考之路
    VB成员函数集锦
    关于软件维护问题的几点思考
    element样式调整用到的东西
    JS实现旋转的魔方
    关于echarts 重绘/图表切换/数据清空
    CSS3 @keyframes 实现匀速旋转魔方(搬运工)
    在vue的js文件引入自定义js文件
    记录 vue+element树节点的标注
    echarts 设置图例文本不可点击
  • 原文地址:https://www.cnblogs.com/chucklu/p/11649980.html
Copyright © 2011-2022 走看看