ajax傳遞對象參數,后台使用FromBody接收對象參數


后端:

1、Modal:創建一個模型參數對象usermsg

public class usermsg
    {
        public string username { get; set; }

        public string password { get; set; }
    }

2、Controllers:將該對象類型作為參數類型

 

前端:

1、HTML:添加一個按鈕button3

 

 

2、javascript事件:為button3添加一個事件

與傳遞字符串相比有兩個不同點:

  其一:ajax對象參數多了一個屬性contentType,值為application/json

  contentType:'application/json'

  其二:data參數中需要將對象序列化為json字符串

  data:JSON.stringify({username: 'zhangsan', password: '123456789'})
$('#btnGetUser').click(function(){
        $.ajax({
            url:'http://localhost:53179/values/api/getuser',
            dataType:'json',
            type:'Post',
            contentType:'application/json',
            data:JSON.stringify({username: 'zhangsan', password: '123456789'}),
            success:function(res){
                console.log(res)
                if(res!=null){
                    $('#name').prop('value',res.username);
                    $('#age').prop('value',res.age);
                }
            }
        })
    });

 

測試:


免責聲明!

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



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