【问题标题】:Javascript get data from Web ServiceJavascript 从 Web 服务获取数据
【发布时间】:2018-04-24 14:06:14
【问题描述】:

我是 Web 应用程序开发的新手,我正在尝试创建一个登录页面并使用 javascript 从本地数据库中获取用户数据。但是我很难找到我做错了什么。这是我的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"')
        }
    });
}



});

我正在使用这些代码使用 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;
        }
    }
}

但在尝试通过填写用户名和密码登录时,我在控制台上遇到此错误

谁能帮忙看一下,不胜感激

编辑 1:

这是服务器类的代码

    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;
        }
    }
    }

连接字符串在我的 web.config 中定义

编辑 2:

这是我的 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>

【问题讨论】:

  • 你能包含你的服务器代码的类定义吗?另外,很高兴看到您正在使用 SQL 参数,因为您是 Web 开发新手 :)
  • @James 请查看编辑。你是这个意思吗?谢谢你,但我不能让它工作。
  • 您的LogIn.asmx.cs 中有什么内容?
  • @PatrickHofman 这是我的网络服务代码所在的位置。这是第二个代码块。
  • 显示它的完整代码。

标签: javascript c# ajax web-services


【解决方案1】:

这是一个棘手的问题。我花了一些时间才意识到这个问题。该错误表示它无法创建Wishlist_2017.Web_Service.LogIn 的实例。您提供的文件似乎表明它在它应该在的位置,并且文件似乎没问题。

但是,在构造函数上下文中,有这样的调用:dbconn dbcon = new dbconn();。如果那个失败,它可能会导致类型创建以一种不太具体的方式失败。

进一步分析,似乎dbconn文件有类似的初始化连接方式:

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

如果那个失败,dbconn 的创建将失败,LogIn 将随后失败。连接字符串似乎有另一个名称或某些配置无效。

尝试从dbconn 中删除objConn 初始化是否解决了类型创建问题。

【讨论】:

  • 同意,命名空间看起来不错,唯一阻止类实例化的就是web.config 中没有Server 连接字符串。
  • 我就是这么想的 :) @James
  • 我尝试使用 web.config 上的凭据,但我的凭据似乎是正确的。请在我的帖子中查看编辑
  • 是的,但是上面的名字是错误的,或者别的什么,但是那个调用导致了它。
  • @VianOjedaGarcia 将dbconn dbcon = new dbconn(); 更改为dbconn dbcon = null,这将排除我们的思路。它仍然会失败,但你会得到一个不同的错误(很可能是NullReferenceException
【解决方案2】:

非常微妙的问题,但您的连接字符串行是问题,即

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

ConnectionStrings['xxx'] 返回一个对象而不是字符串本身,你想要

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

【讨论】:

  • 是的,但这会重现问题中的另一个错误。
  • @PatrickHofman 认为这确实解决了问题中的问题,除非我错过了另一个错误?我只能看到一个。
  • ToString 不会让类的实例化失败。它仍然会重现一个字符串,尽管是无效的。稍后,它会因为无效的连接字符串而失败,但那是在创建类之后很久。
  • @PatrickHofman 是的......这是真的,除非配置不存在(它似乎存在),否则ToString 不太可能抛出。
  • 我认为这是因为我的网络配置上的连接字符串。因为同样的课程适用于我的朋友
【解决方案3】:

永远不要手动创建 json。这比在您使用的任何语言中使用 json 序列化程序更耗时且容易出错。

由于引用不当,您正在创建的内容无效!

在对象上使用JSON.stringify()

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

【讨论】:

  • 这不是问题。您正在解决另一个问题(并复制已删除的答案,如您所见)。
  • @PatrickHofman 必须具有有效的 JSON 才能开始。删除的答案仍然使用无效引号。也许还有其他后端问题,但至少有有效的输入会有所帮助
猜你喜欢
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 2013-07-09
  • 2018-07-03
相关资源
最近更新 更多