简体   繁体   English

jQuery ajax dataType="json" 与 JSON.parse() 有什么区别

[英]What's diffrence in jQuery ajax dataType="json" vs JSON.parse()

Is there any real diffrence between using dataType='json' and parse response by JSON.parse(response) in jQuery Ajax?在 jQuery Ajax 中使用 dataType='json' 和通过 JSON.parse(response) 解析响应之间是否有任何真正的区别?

$.ajax({
        url: path,
        type: 'POST',
        dataType: 'json',
        data: {
            block : lang,
        },
    }).done(function(response, textStatus, jqXHR)
    {
        output = response;
    });

VS VS

    $.ajax({
        url: path,
        type: 'POST',
        data: {
            block : lang,
        },
    }).done(function(response, textStatus, jqXHR)
    {
        output = JSON.parse(response);
    });

dataType: 'json' : dataType: 'json'

  • Sets the Accept request header to tell the server that JSON is the desired response format设置Accept请求 header 告诉服务器 JSON 是所需的响应格式
  • Attempts to parse the response as JSON regardless of what the server's Content-Type response header says the format is.尝试将响应解析为 JSON 而不管服务器的Content-Type响应 header 所说的格式是什么。 (jQuery's default behaviour is to use the Content-Type to determine the correct parser). (jQuery 的默认行为是使用Content-Type来确定正确的解析器)。

JSON.parse : JSON.parse

  • Attempts to parse the response data as a string of JSON regardless of what it actually is (if the server responds with correctly labelled JSON, this will error since it will have already been parsed by jQuery).尝试将响应数据解析为 JSON 的字符串,无论它实际上是什么(如果服务器以正确标记的 JSON 响应,这将出错,因为它已经被 jQuery 解析)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM