axios与ajax和fecth使用方式

//axios不支持jsonp格式

axios({

method:'post',

url:'http://127.0.0.1:3000/user',

params:{phoneNum:1}

})

.then(function(data) {

console.log(data.data)

});

那么如果要使用jsonp,可以独立安装
npm i jsonp --save-dev 然后在页面中引用import jsonp from 'jsonp',使用方式也是非常简单的:

getList: function () {
 jsonp(config.ajaxUrl + '路径', null, (err, data) => {
   if (err) {
     console.error(err.message);
   } else {
     if (data.list.length > 0) {
       data.list.map((item) => this.list.push(item))
       console.log(data);
     }
   }
 })
}

$.post("http://127.0.0.1:3000/user/outmoney",{phoneNum:1},function(data){

  console.log(data)

})

$(function(){
    $('#send').click(function(){
         $.ajax({
             type: "GET",
             url: "test.json",
             data: {username:$("#username").val(), content:$("#content").val()},
             dataType: "json",
             success: function(data){
                         $('#resText').empty();   //清空resText里面的所有内容
                         var html = ''; 
                         $.each(data, function(commentIndex, comment){
                               html += '<div class="comment"><h6>' + comment['username']
                                         + ':</h6><p class="para"' + comment['content']
                                         + '</p></div>';
                         });
                         $('#resText').html(html);
                      }
         });
    });
});
fetch(url,function(){
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
method: 'POST',
body: data
}).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(e) {
  console.log(e);
});
vue-resource

get方法

this.$http.get("http://localhost/test.php")

.then( function (res) {

// 处理成功的结果 console.log(res.body); },

function (res) { // 处理失败的结果 } );

post方法

this.$http.post("http://localhost/test.php",

{name:"zhangsan"},{emulateJSON:true})

.then( function (res) { // 处理成功的结果 console.log(res.body); },

function (res) { // 处理失败的结果 } );

猜你喜欢

转载自blog.csdn.net/namechenfl/article/details/81224161