前端通过ajax请求,调用net core webapi接口

一、前段HTML

1、引入jquery文件:https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js

2、编写js事件,事件触发时调用该ajax请求。

  2.1、jquery封装了一个ajax的方法。参数是一个对象。这个对象包含以下属性:

    请求地址:URL:   'http://IP地址/端口/接口地址'

    请求方式:type:'get/post/put/delete'

    请求数据类型:datatype: 'json'

    请求数据:data: '{uname: "zhangsan", pwd:'123456'}'

    请求回调函数:success function(data){}, error function(data){}

 以上代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
	<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
	<input type="text" id="name"/>
	<input type="text" id="age"/>
    <input type="button" id="btnCommit" onclick="ajaxFunc()" value="button"/>
	<input type="button" id="btnClear" value="Clear">
</body>
<script>

    function ajaxFunc() {
            $.ajax({
		    url: "http://localhost:53179/api/values/post",
		    type: 'post', 
            dataType: 'json',
            data: {id:22},
		    success: function (res) {
			       console.log(res)  
					if(res!=null){
						$('#name').attr('value',res.username);
						$('#age').attr('value',res.age);
					}
	         },
			error function(res){
				console.log(res);
			},
			complete function(status){
				console.log(res);
			}
	    })
    };
	
	$('#btnClear').on('click',function(){
		$('#name').val("");
		$('#age').val("");
	});
	
    
</script>

</html>

后端net core web api

1、创建一个工程项目之后,添加一个控制器继承Controller

1.1编写接口(这里没有使用数据库),主要是测试前端请求之后能否执行调用该接口

 2、调试接口正常,但是会发现,前段调用的时候会出现跨域问题。

解决如下:在startup类配置跨域

services.AddCors(options => options.AddPolicy("DomainKYHttp",
                                         builder => builder.AllowAnyMethod()
                                         .AllowAnyHeader()
                                         .AllowAnyOrigin()
                                         .AllowCredentials()));
                                           

最后运行后台代码,使用浏览器打开第一步创建的html。测试成功

原文地址:https://www.cnblogs.com/ZM191018/p/13813180.html