为什么需要在JQuery ajax中包含dataType

时间:2019-05-02 08:09:51

标签: javascript jquery json ajax

我有下一个代码:

$.ajax({
     type: "GET",
     url: url,
     data: {language: language},
     contentType: "application/json",
     success: function (result) {
        console.log(result);
        result.forEach(function(item) {
           var option = $("");
           option.text(item);
           option.val(item);
           node.append(option);
        });
        if (self.value.country) {
            $("#countrySelect").val(self.value.country);
        }
    }
});

为什么在第一种情况下(当我刷新页面或第一次访问它时)它返回json而在下一种情况下(回发)它返回字符串 然后我添加

dataType: "json"
现在,它仅返回json。 为什么不添加就无法正常工作? 1)的数据类型为enter image description here

2)没有dataType(首次加载)enter image description here 3)没有dataType(回发)enter image description here

1 个答案:

答案 0 :(得分:1)

由于未指定dataType,因此需要猜测类型。通过将其指定为JSON,它将期望JSON数据响应。您也不能指定多种数据类型-如果需要返回不同的数据类型,则必须将其设置为默认值。