jQuery Ajax返回字符串而非对象,如何配置使其像Axios一样返回对象?
问题:jQuery AJAX请求返回字符串而非对象,如何配置成Axios那样自动解析?
我用React开发时,写了获取JSON数据的代码,Axios请求能正常返回对象类型的响应数据,但换成jQuery后,返回的response.data是字符串类型。业务要求必须替换成jQuery,希望不用手动对响应做后处理,通过配置jQuery参数实现和Axios一致的效果。
项目代码
import React from 'react'; import axios from 'axios'; import $ from 'jquery'; import './style.css'; export default () => { const jsonSource = 'https://raw.githubusercontent.com/tlg-265/mockend/master/data.json'; const handleClickAxios = () => { axios.get(jsonSource).then(response => { console.log({ responseType: (typeof response.data)}); console.log(response.data); }); }; const handleClickJQuery = () => { sendApiRequest({ url: jsonSource, method: 'get' }).then(response => { console.log({ responseType: (typeof response.data)}); console.log(response.data); }); }; return ( <div> <h1>Axios vs jQuery</h1> <p><b>Inconsitency:</b> returning response as Object vs String</p> <button onClick={handleClickAxios}>Axios</button>{' '} <button onClick={handleClickJQuery}>jQuery</button> </div> ); }; export const sendApiRequest = ({ url, method, data, timeout, }) => { method = method.toUpperCase(); let additionalSettings = { data: data }; if (method === 'POST') { additionalSettings = { contentType: 'application/json', dataType: 'json', data: JSON.stringify(data), }; } return new Promise((resolve, reject) => { $.ajax({ url, method: method, timeout, ...additionalSettings, success: (response) => { resolve({ data: response }); }, error: ({ responseJSON }) => { reject(responseJSON); }, }); }); };
解决方案
核心是给jQuery的$.ajax配置dataType: 'json'参数,这个参数会告诉jQuery自动把响应的JSON字符串解析成JavaScript对象,和Axios的默认行为完全一致。
修改代码:
在sendApiRequest函数中,给所有请求(包括GET)添加dataType: 'json'配置:
export const sendApiRequest = ({ url, method, data, timeout, }) => { method = method.toUpperCase(); // 给默认配置加上dataType: 'json',让GET请求也自动解析JSON let additionalSettings = { data: data, dataType: 'json' }; if (method === 'POST') { additionalSettings = { contentType: 'application/json', dataType: 'json', data: JSON.stringify(data), }; } return new Promise((resolve, reject) => { $.ajax({ url, method: method, timeout, ...additionalSettings, success: (response) => { resolve({ data: response }); }, error: ({ responseJSON }) => { reject(responseJSON); }, }); }); };
原因说明:
之前的问题是GET请求没有配置dataType,jQuery默认把响应当成纯文本返回字符串;而POST请求因为配置了dataType: 'json',所以能正常解析成对象。现在给所有请求统一加上这个配置,就能和Axios一样自动返回解析好的对象了,不需要手动调用JSON.parse()做后处理。
内容的提问来源于stack exchange,提问作者Viewsonic
相关产品推荐
相关产品推荐

