简体   繁体   English

Javascript从Web服务获取数据

[英]Javascript get data from Web Service

I am new to web app development I am trying to make a log in page and get the data of user from a local database using javascript. 我是Web应用程序开发的新手,我试图制作一个登录页面,并使用javascript从本地数据库获取用户数据。 But I am having trouble finding where I did something wrong. 但是我很难找到我做错了什么地方。 Here is my javascript code 这是我的JavaScript代码

$(document).ready(function () {

$("#log-in-form").on("submit", function (e) {
    e.preventDefault();

    var username = $(this).find("input[type=text]").val();
    var password = $(this).find("input[type=password]").val();

    Authentication(username, password);

});

function Authentication(username,password){
    $.ajax({

        type: "GET",
        url: "../Web Service/LogIn.asmx/get_uinfos",
        data: "{'domain':" + username + "', 'accountpassword':'" + password + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var result = response.d;
            var length = response.length;

            $.each(result, function (index, data) {
                var alias = data.alias;
                window.localStorage.replace("Main.aspx");
            });
        },
        error: function () {
            alert('Function Error "get_uinfos"')
        }
    });
}



});

and I am connecting to the local server using web service using these code 我正在使用这些代码使用Web服务连接到本地服务器

using Wishlist_2017;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Services;
using System.Web.Services;


namespace Wishlist_2017.Web_Service
{
    /// <summary>
    /// Summary description for LogIn
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class LogIn : System.Web.Services.WebService
    {
        dbconn dbcon = new dbconn();

        public class uinfos
        {
            public int id;
            public string alias;
            public string monito;
        }

        static List<uinfos> _get_uinfos = new List<uinfos> { };
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        [WebMethod]
        public List<uinfos> get_uinfos(string domain, string accountpassword)
        {
            DataTable table = null;
            SqlCommand cmd = new SqlCommand();

            cmd.CommandText = "Retrieve_UserInfo";

            cmd.Parameters.AddWithValue("@Domain", domain);
            cmd.Parameters.AddWithValue("@Password", accountpassword);

            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            table = this.dbcon.ExecuteDataTable(cmd);

            _get_uinfos.Clear();

            foreach (DataRow row in table.Rows)
            {
                uinfos _list = new uinfos();

                _list.id = Convert.ToInt32(row["id"]);
                _list.alias = row["Alias"].ToString();
                _list.monito = row["Monito"].ToString();

                _get_uinfos.Add(_list);
            }

            return _get_uinfos;
        }
    }
}

but upon trying to log in by filling the username and password I encounter this error on the console 但是在尝试通过填充用户名和密码登录时,我在控制台上遇到此错误

在此处输入图片说明

can someone help where to look it will be much appreciated 有人可以帮忙看哪里,将不胜感激

EDIT 1: 编辑1:

This is the code for the class of server 这是服务器类的代码

    using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace Wishlist_2017
{
    public class dbconn
    {
        string objConn = ConfigurationManager.ConnectionStrings["Server"].ToString();

        public dbconn()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public DataTable ExecuteDataTable(SqlCommand cmd)
        {
            DataTable dt = new DataTable();

            using (SqlConnection cn = new SqlConnection(objConn))
            {
                try
                {
                    cn.Open();
                    cmd.Connection = cn;
                    cmd.CommandTimeout = 1000;

                    SqlDataAdapter da = new SqlDataAdapter(cmd);

                    da.Fill(dt);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (cn.State != System.Data.ConnectionState.Closed)
                        cn.Close();
                }

                return dt;
            }
        }

        public void ExecuteNonQuery(SqlCommand cmd)
        {
            using (SqlConnection cn = new SqlConnection(objConn))
            {
                try
                {
                    cn.Open();
                    cmd.Connection = cn;
                    cmd.CommandTimeout = 1000;
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (cn.State != System.Data.ConnectionState.Closed)
                        cn.Close();
                }
            }
        }


        public object ExecuteScalar(SqlCommand cmd)
        {
            object result = null;

            using (SqlConnection cn = new SqlConnection(objConn))
            {
                try
                {
                    cn.Open();
                    cmd.Connection = cn;
                    cmd.CommandTimeout = 1000;
                    result = cmd.ExecuteScalar();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (cn.State != System.Data.ConnectionState.Closed)
                        cn.Close();
                }
            }

            return result;
        }
    }
    }

the connection string is defined on my web.config 连接字符串在我的web.config中定义

EDIT 2: 编辑2:

This is the connection string on my web.config 这是我的web.config上的连接字符串

<connectionStrings>
  <add name="Server" connectionString="Data Source=(LocalDB)\ArnServer; initial Catalog=Wishlist; uid=sa; pwd=ordiz@2017!; Asynchronous Processing=true" providerName="System.Data.SqlClient"/>
</connectionStrings>

This is a tricky one. 这是一个棘手的问题。 It took me some time to realize the issue. 我花了一些时间才意识到这个问题。 The error said it can't create an instance of the Wishlist_2017.Web_Service.LogIn . 该错误表明它无法创建Wishlist_2017.Web_Service.LogIn的实例。 The files you supply seem to indicate it is there where it should be and the file seems okay. 您提供的文件似乎表明它应该存在,并且文件似乎还可以。

However, in the constructor context, there is this call: dbconn dbcon = new dbconn(); 但是,在构造函数上下文中,存在以下调用: dbconn dbcon = new dbconn(); . If that one fails, it might cause the type creation to fail in a not very specific way. 如果该操作失败,则可能导致类型创建失败,方式不是非常明确。

Analyzing further, it seems that the dbconn file has a similar way of initializing the connection: 进一步分析,似乎dbconn文件具有类似的初始化连接的方式:

string objConn = ConfigurationManager.ConnectionStrings["Server"].ToString();

If that one fails, the creation of dbconn will fail and the LogIn will fail subsequently. 如果该操作失败,则dbconn的创建将失败,并且LogIn随后将失败。 It seems the connection string has another name or there is some configuration invalid. 似乎连接字符串具有其他名称,或者某些配置无效。

Try to see if removing the objConn initialization from dbconn solves the type creation problem. 尝试查看从dbconn删除objConn初始化dbconn解决了类型创建问题。

Very subtle issue but your connection string line is the problem ie 非常细微的问题,但是您的连接字符串行就是问题,即

string objConn = ConfigurationManager.ConnectionStrings["Server"].ToString();

ConnectionStrings['xxx'] returns an object and not the string itself, you want ConnectionStrings['xxx']返回一个对象,而不是字符串本身

string objConn = ConfigurationManager.ConnectionStrings["Server"].ConnectionString; 

Never ever manually create json. 永远不要手动创建json。 It is more time consuming and error prone than using a json serializer in whatever language you are working with. 与使用您使用的任何语言的json序列化程序相比,它更耗时且更容易出错。

What you are creating is invalid due to improper quotes! 您创建的内容因报价不正确而无效!

Use JSON.stringify() on an object instead 在对象上使用JSON.stringify()代替

data: JSON.stringify({'domain': username , 'accountpassword':  password }),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM