jQuery的Ajax调用数据库上点击ASP.net [英] jQuery Ajax call to database on click ASP.net

查看:181
本文介绍了jQuery的Ajax调用数据库上点击ASP.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有,看起来像

Let's say I've got a table in a SQL Server database that looks like

StateName  notes
alabama    'notes about alabama'
alaska     'notes about alaska'
.....      .........

编辑:这个问题将分为两个部分,一个是最初的问题,为什么它没有工作,我的改革,希望能更准确的第二个解决方案

This question will be divided into two parts, one for the initial problem and why it didn't work and my reformed, hopefully more accurate second solution.

在Web表单,国家的名称表示为表内的链接按钮。我试图使用jQuery,当用户点击一个国家的名字,使一个Ajax调用数据库,链接按钮的文本值将被发送到数据库的存储过程。
该存储过程是一样的东西。

In the web form, the name of the state are represented as link button inside of a table. I'm trying to use jQuery to make an Ajax database call when a user clicks on a state name, the text value of the link button will be send to a stored procedure in the database. That stored procedure is something like

create proc spGetStateData
@stateName varchar(50)
as
begin
select notes from 
states
where statename = @stateName
end

有关测试的目的,我加了AA文本框和一个按钮,这样,当用户键入状态到文本框中的名称,注释美国列<显示/ code>数据库表。

For testing purposes, I added a a text box and a button so that when the user types the name of the state into the text box, the Notes column from the States database table is displayed.

[WebMethod]
        public static string GetStateData(string stateName)
        {
            string stateNotes = string.Empty;
            string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                using (SqlCommand cmd = new SqlCommand("spGetStateData", con))
                {
                    con.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@stateName", stateName);
                    stateNotes = cmd.ExecuteScalar().ToString();
                }
            }
            return stateNotes;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            lblStateNotes.Text = GetStateData(txtStateName.Text);
            hiddenDiv.Visible = true;
        }

这部分的作品,所以我知道这不是我的WebMethod,或者是一个数据库连接失败。当我尝试这样做与jQuery同样的事情,它失败。

This part works, so I know it's not my WebMethod or a database connection that's failing. When I try to do this same thing with jQuery, it fails.

<script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#states a").click(function () {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "WebForm1.aspx/GetStateData",
                    data: $(this).text(),
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (x) {
                        alert('error');
                    }
                });
            });
        });

    </script>



好吧,我把Chrome浏览器开放的开发工具和发现了什么的AJAX失败的原因是我得到一个无法加载资源HTTP 500错误。有人告诉我,方法名和参数无法找到(即使所有权利。他们在那里)。于是我尝试了第二种方式,这似乎是一个更好的方法(如果我能得到它的工作!)

Okay, I pulled open developer tools for Chrome and found out what the reason for the AJAX failing was that I was getting a 'couldn't load resource HTTP 500 error'. It was telling me that the method name and parameter couldn't be found (even though by all rights they were there). So then I tried a second way, which seems like a better way (if I can get it to work!)

于是我想'让我们用一个WebService。这里是我的翻译是:

So then I thought 'let's use a WebService'. And here is my rendition of that:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("a").click(function () {
                var stateName = JSON.stringify({ "stateName": $(this).text() });
                $.ajax({
                    type: "POST",
                    url: "GetStateData.asmx/GetData",
                    contentType: "application/json; charset=utf-8",
                    data: stateName,
                    dataType: "json",
                    success: function (data) {
                        $("#lblNotes").text(data);
                    },
                    error: function (x) {
                        alert('message');
                    }
                });
            });

        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <a href="#">Alabama</a>
    <a href="#">Alaska</a>
    <asp:Label runat="server" ID="lblNotes"></asp:Label>

    </div>
    </form>
</body>
</html>



Web服务:

web service:

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

namespace jQueryAjaxWebservice
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    [System.Web.Script.Services.ScriptService]    
    public  class GetStateData : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod]
        public string GetData(string stateName)
        {
            string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
            string stateNotes ="test" ;
            using (SqlConnection con = new SqlConnection(cs))
            {
                using (SqlCommand cmd = new SqlCommand("spGetStateData",con))
                {
                    con.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@stateName", stateName);
                    stateNotes = cmd.ExecuteScalar().ToString();
                }

            }
           return stateNotes;
        }
    }
}



我测试过的web服务,和它的作品。然而,当我尝试调用从Default.aspx的Web服务代码,我得到 [Object对象] lblNotes 文本。如果我改变(数据),以测试然后我得到测试的正确的输出到屏幕上。因此,故障部件是在成功 Ajax调用的一部分。我把一个断点在GetData函数和 stateNotes 正在接受正确的文本值,所以要离开这个问题的唯一地方是在成功 Ajax调用的行。

I've tested the WebService, and it works. However, when I try to call the web service code from default.aspx, I get [Object object] as the lblNotes text. If I change (data) to "test" then I get the correct output of "test" to the screen. So the faulty part is in the success portion of the Ajax call. I put a breakpoint on the GetData function and stateNotes is receiving the proper text value, so the only place left for the problem to be is in the success line of the ajax call.

推荐答案

我觉得你格式化你的 AJAX 选项>可能是错的。它始终工作在键 - 值对。在目前的形式,你只能送价值,没有钥匙。您可能必须将其更改为格式为:

I think the way you format your data option in ajax might be wrong. It always works in key-value pairs. In the current form you are only sending the value, no key. You might have to change it to this format :

var stateName = { "stateName" : $(this).text()}

var stateName = JSON.stringify({ "stateName" : $(this).text()})

但总的来说,我只看到了第二个工作,部分原因是因为jQuery的不的预处理的的数据对于它的选择是C#的可读性。所以它总是推荐使用字符串化 AJAX 请求类型设置为POST

But mostly, I've seen only the second one to work, partly because jQuery doesn't pre-process the data option for it be readable in C#. So it's always recommended to use stringify on ajax requests with type set to "POST".

然后,在你的 AJAX 调用

$.ajax({
   //ajax options
   data : stateName
   //some more ajax options
});



此外,您可能想使你的错误选项的详细描述,如:

Also, you might want to make your error option more descriptive, like this :

 $.ajax({
       //ajax options
       error: function (xhr, ajaxOptions, thrownError) {
         alert(xhr.status);
         alert(thrownError);
       }
 });

这会告诉你,你要去哪里错了,你可以调试它。

This will tell you where you're going wrong and you could debug it as well.

编辑:

成功功能,尝试寻找 data.d 而不是数据。你会发现,你的数据就在于里面。此外,如前面提到的( ,我不能强调这一点),请使用错误处理与 XHR 选项。它会更容易调试即可。 阅读本返回 data.d 而不仅仅是数据

In the success function, try looking for data.d instead of data. You'll find that your data lies inside it. Also, as mentioned before (and i cant stress this enough), please use error handler with xhr options. It'll be easier to debug then. Read this if you want to know why the result returns data.d and not just data.

$.ajax({
   //some ajax options
   success: function (data) {
        //data.d will contain your data
        console.log(data.d);
        $("#lblNotes").text(data.d);
   },
   error: function (xhr, ajaxOptions, thrownError) {
         console.log(xhr);
         alert(xhr.status);
         alert(thrownError);
   }
});



希望这有助于!

Hope this helps!

这篇关于jQuery的Ajax调用数据库上点击ASP.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆