首先在asp.net项目中的web.config中加入:
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/> <add name="Access-Control-Allow-Headers" value="x-requested-with,content-type,Accept"/> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> </system.webServer>
然后在AppCode中的WebService.cs中加入:
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 // [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { [WebMethod(Description = "GetUserinfoList")] public string GetUserinfoList() { DataSet ds = null; string json = ""; string sql = ""; try { SqlParameter[] paras = new SqlParameter[1]; paras[0] = new SqlParameter("@today", SqlDbType.VarChar); paras[0].Value = ""; sql = @"select * from Userinfo"; ds = SqlHelper.ExecuteDataset(getLocalConnection(), CommandType.Text, sql, paras); if (ds == null || ds.Tables[0].Rows.Count == 0) json = ""; else json = JsonConvert.SerializeObject(ds.Tables[0], new DataTableConverter()); } catch (Exception ex) { json = ""; } return json; }
然后在vue的项目中引入js:
npm install jquery --save
然后在vue.config.js加入:
const webpack = require('webpack') module.exports = { devServer: { overlay: { warnings: false, errors: false } }, lintOnSave: false, publicPath: './', chainWebpack: config => { config.plugin('provide').use(webpack.ProvidePlugin, [{ $: 'jquery', jquery: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }]) } }
然后在页面中这么来使用:
<template> <el-table :data="userData" border style="width: 100%"> <el-table-column prop="UserId" label="Id" width="180"> </el-table-column> <el-table-column prop="UserName" label="姓名" width="180"> </el-table-column> <el-table-column prop="Address" label="地址"> </el-table-column> </el-table> </template> <script> import {tqData,getUser} from '@/network/networks' import $ from 'jquery' import axios from "axios"; export default { mounted() { var _this = this; $.ajax({ type: "post", url: "http://localhost:57651/WebService.asmx/GetUserinfoList", //接口地址,后面加上 /方法名即可 contentType: "application/json", dataType: "json", success: function (inf) { _this.$nextTick(() => { _this.userData = JSON.parse(inf.d); //将获取的JSON字符串转化成JSON对象 console.log("<<<111"); console.log(this.userData); _this.itemkey = Math.random(); }); }, error: function () { alert("获取数据失败!"); } }); }, methods:{ }, data() { return { itemkey:'', userData: [] } } } </script>