将 jQuery 请求转换为 Axios
Converting jQuery Request to Axios
我有一个用 jQuery 编写的应用程序。我正在努力使它现代化。作为其中的一部分,我正在尝试将 jQuery 请求转换为 Axios。我的 jQuery 请求如下所示:
var myUrl = '[someUrl]';
var myData = {
firstName: 'Joe',
lastName: 'Smith'
};
$.ajax({
type: 'POST', url: myUrl, cache: 'false',
contentType:'application/json',
headers: {
'Content-Type': 'application/json',
'key': '12345'
},
data: JSON.stringify(myData),
success: onSearchSuccess,
error: onSearchFailure,
complete: onSearchComplete
});
现在,使用我的现代代码,我有以下内容:
var myUrl = '[someUrl]';
var myData = {
firstName: 'Joe',
lastName: 'Smith'
};
axios.post(myUrl, myData)
.then(function (response) {
alert('yeah!');
console.log(response);
})
.catch(function (error) {
alert('oops');
console.log(error);
})
;
我不确定如何传入 headers 或者我是否需要对 myData
进行字符串化。有人可以指出我正确的方向吗?
你试过manual了吗? :)
这是您需要的:
axios.post(url[, data[, config]])
将其转化为代码的方式是:
var myUrl = '[someUrl]';
var myData = {
firstName: 'Joe',
lastName: 'Smith'
};
axios.post(myUrl, myData, {
headers: {
'Content-Type': 'application/json',
'key': '12345'
}
// other configuration there
})
.then(function (response) {
alert('yeah!');
console.log(response);
})
.catch(function (error) {
alert('oops');
console.log(error);
})
;
返回的对象实现了A+ Promise API. Based on your configuration you may need to polyfill that, but there are a lot of packages available on in the npm registry.
我有一个用 jQuery 编写的应用程序。我正在努力使它现代化。作为其中的一部分,我正在尝试将 jQuery 请求转换为 Axios。我的 jQuery 请求如下所示:
var myUrl = '[someUrl]';
var myData = {
firstName: 'Joe',
lastName: 'Smith'
};
$.ajax({
type: 'POST', url: myUrl, cache: 'false',
contentType:'application/json',
headers: {
'Content-Type': 'application/json',
'key': '12345'
},
data: JSON.stringify(myData),
success: onSearchSuccess,
error: onSearchFailure,
complete: onSearchComplete
});
现在,使用我的现代代码,我有以下内容:
var myUrl = '[someUrl]';
var myData = {
firstName: 'Joe',
lastName: 'Smith'
};
axios.post(myUrl, myData)
.then(function (response) {
alert('yeah!');
console.log(response);
})
.catch(function (error) {
alert('oops');
console.log(error);
})
;
我不确定如何传入 headers 或者我是否需要对 myData
进行字符串化。有人可以指出我正确的方向吗?
你试过manual了吗? :)
这是您需要的:
axios.post(url[, data[, config]])
将其转化为代码的方式是:
var myUrl = '[someUrl]';
var myData = {
firstName: 'Joe',
lastName: 'Smith'
};
axios.post(myUrl, myData, {
headers: {
'Content-Type': 'application/json',
'key': '12345'
}
// other configuration there
})
.then(function (response) {
alert('yeah!');
console.log(response);
})
.catch(function (error) {
alert('oops');
console.log(error);
})
;
返回的对象实现了A+ Promise API. Based on your configuration you may need to polyfill that, but there are a lot of packages available on in the npm registry.