Vue开发学习笔记:Vue项目使用Ajax调用C#WebService

1.Vue组件中

import $ from 'jquery'//项目开发时手工添加
export default {
    components: {
        'px-menu': PXMenu
    },
    data(){
        return{
            msgFromDb: ''
        }
    },
    created: function name(params) {
        var self=this;
        $.ajax({
            type: "post",//请求方式
            url: "http://localhost/PaladinXuWebService/PXWebService.asmx/ExcuteSelect",//正式链接
            data: {sql:"SELECT * FROM TUSERINFO"},//传入参数
            dataType: "json",//数据类型
            success: function (response) {//成功回调
                // self.msgFromDb=JSON.parse(response);
                // console.log(response);
                console.log(response);
                self.msgFromDb=response;
            },
		    error:function(ex){//失败回调
                // alert("获取数据失败!"+ex);
                // console.log(ex.responseText);
                // self.msgFromDb=JSON.parse(ex.responseText);
	    	}

            
            
        });
    }
    
}

注意:一定要引用import $ from 'jquery'//项目开发时手工添加,否则在运行时会提示$未定义

2.在WebService中

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace MyWebService
{
    /// <summary>
    /// PXWebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class PXWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod(Description="查询")]
        public string ExcuteSelect(string sql)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();//用于序列化和反序列化
            System.Collections.ArrayList dic = new System.Collections.ArrayList();
            //MyDataSet inDs=new MyDataSet();
           // MyDataSet outDs = DBManager.CallService(serviceName, inDs);
            DataSet ds = new DataSet();
            DBManager.ExcuteSelect(sql, ds);//执行对应的SQL以及返回查询结果

            //将返回结果集(DataTable)转为数组
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    System.Collections.Generic.Dictionary<string, object> drow = new System.Collections.Generic.Dictionary<string, object>();
                    foreach (DataColumn dc in ds.Tables[0].Columns)
                    {
                        drow.Add(dc.ColumnName, dr[dc.ColumnName]);
                    }
                    dic.Add(drow);
                }
            }

            //将对象转为JSON字符串
            string json_table = jss.Serialize(dic);
            //返回之前使用以下两句代码,可以去除转为json格式后值多出来的xml标签
            //同时如果不使用下面两句代码,Vue项目在请求时无法走成功回调函数而是进失败回调函数
            Context.Response.Write(json_table);//写入输出流
            Context.Response.End();//将所有的输出流发送到客户端
            return json_table;
        }
    }
}

注意:1.在WebService方法中一定要加上

Context.Response.Write(json_table);//写入输出流
Context.Response.End();//将所有的输出流发送到客户端

 否则Vue项目中调用时无法走成功回调函数,而是进入失败回调函数,同时还能将转为JSON之后的字符中多余的xml标签去除

2.在WebService中一定要在WebConfig中添加一段代码(学习自:https://www.cnblogs.com/masha2017/p/12840963.html)

<!--添加一下代码解决Vue项目使用Ajax访问WebService时提示跨域请求的错误-->
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <!--Value="*"不限制域名 -->
        <add name="Access-Control-Allow-Origin"  value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

否则在Vue项目调用方法时会如下错误

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值