js 調用接口並傳參


注:需先引入 jquery.json-xx.min.js

 

1. 參數跟在url后面

var name = '王一';
var age = 18;
$.ajax({
    type : 'get',
    url : "xxxxxx?name="+name+"&age="+age,
    async : false,//同步/異步
    contentType : "application/x-www-form-urlencoded; charset=gbk",
    dataType : 'json', //返回 JSON 數據
    beforeSend : function() { //調用前觸發,如加載效果等
        show('.load'); 
    },
    success : function(data, status) {
        var rstate = data.result;
        if (rstate == "0") {
            alert('接口調用成功!');
        } else {
            alert('接口調用失敗!');
        }
    },
    complete : function() { //調用后觸發(不管成功或失敗)
        hide('.load);
    },
    error : function(data, status, e) {
        alert('接口調用錯誤!');
    }
});

 

 

2. 參數在data內

$.ajax({
    type : 'get',
    url : 'xxxxx',
    async : false,
    contentType : "application/x-www-form-urlencoded; charset=gbk",
    data : {
        'name': '王一', //json格式 'age': '18'
    },
    dataType : 'json',
    beforeSend : function() { 
        show('.load'); 
    },
    success : function(data, status) {
        var rstate = data.result;
        if (rstate == "0") {
            if (rstate == "0") {
            alert('接口調用成功!');
        } else {
            alert('接口調用失敗!');
        }
    },
    complete : function() { 
        hide('.load);
    },
    error : function(data, status, e) {
        alert('接口調用錯誤!');
    }
});    

 

 

3. param傳參

var obj = new Object();
obj.name = '王一';
obj.age = 18;
$.ajax({
    type : 'post',//也可為get
    url : 'xxxxx',
    async : false,
    contentType : "application/x-www-form-urlencoded; charset=gbk",
    data : {
        param : $.toJSON(obj) //轉換為json格式
    },
    dataType : 'json',
    beforeSend : function() { 
        show('.load'); 
    },
    success : function(data, status) {
        var rstate = data.result;
        if (rstate == "0") {
            if (rstate == "0") {
            alert('接口調用成功!');
        } else {
            alert('接口調用失敗!');
        }
    },
    complete : function() { 
        hide('.load);
    },
    error : function(data, status, e) {
        alert('接口調用錯誤!');
    }
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM