zoukankan      html  css  js  c++  java
  • 前端通过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。测试成功

  • 相关阅读:
    leetcode100
    leetcode237
    leetcode171
    leetcode122
    leetcode387
    2018-8-10-win10-uwp-如何打包Nuget给其他人
    2018-8-10-win10-uwp-如何打包Nuget给其他人
    2019-11-13-如何在国内发布-UWP-应用
    2019-11-13-如何在国内发布-UWP-应用
    2019-2-21-PowerShell-通过-WMI-获取设备厂商
  • 原文地址:https://www.cnblogs.com/ZM191018/p/13813180.html
Copyright © 2011-2022 走看看