Home Web Front-end JS Tutorial jquery+ajax+C#实现无刷新操作数据库数据的简单实例_jquery

jquery+ajax+C#实现无刷新操作数据库数据的简单实例_jquery

May 16, 2016 pm 05:01 PM
ajax jquery Operation data

我们知道同步执行和异步执行的区别,为了更好的提高用户的体验,我们都会采用异步方式去处理一些问题,毕竟单线程的同步可能回造成卡死等现象,很不友好,所以可以使用ajax来完成用户的体验,现在我们就来说说如何使用jquery的ajax来实现无刷新的获取内容

我们只是单方面的获取内容,分页等就不考虑了,后期会讲到无刷新的分页

页面中我们放置一个Div容器用来存放返回的内容


jquery+ajax+C#实现无刷新操作数据库数据的简单实例_jquery

注:wait.gif是一个类似进度条的效果,当没有加载的内容没有加载出来的时候,就显示这个效果,这样就能提高用户的体验度。然后最重要的就是jquery这块了,需要用到ajax来完成

代码:

复制代码 代码如下:

function getInfo()
{
   $.ajax({
    url:"doAction.aspx?fig=reader&id=1&page=1",
    type:"POST",
    success:function(Data)
    {
      $("#comment").html(Data);
//通过arguments[0]接收也可以 $("#comment").html(arguments[0]); 
    },
    error:function()
    {
alert("程序出错");
    }
   })
}

url:指向的url

type:提交的方式,可以为POST或者GET

success:通信成功后执行的函数

error:通信失败后执行的函数

beforeSend:通信前执行的韩硕

complete:通信完成后执行的函数

在这里采用了POST提交的方式,比Get更安全些,所以也可以替换成下面的方式

复制代码 代码如下:

function getInfo1() {
    $.post("doAction.aspx", { fig: "reader", id:"1", page:"1" }, function () {
 $("#comment").html(arguments[0]);
    })
}

可以看到参数的写法不同,采用POST提交方式,第一种方式和第二种方式区别在于:

首先,接收参数的时候,在doAction.aspx页面里第一种方式使用Request.QueryString["fig"]接收,第二种方式使用的是Request.Form["fig"]

其次,第一种方式当通信失败后,可以友好的返回错误信息,第二种方式暂时没发现可以返回

然后在doAction.aspx页面中,只要进行相应的处理就可以了

复制代码 代码如下:

if (Request.Form["fig"] != null && Request.Form["fig"].ToString() == "reader")
 {
     ajax_getcomment("1",1);
 }
//从数据库中获取数据
    private void ajax_getcomment(string id, int page)
    {

 using (CommentBO cm = new CommentBO(id, page - 1))
 {
     Response.Write(cm.getCommentContent());
 }
    }


同样如果才用Get的提交方式,使用$.get("",{},function(){})也是一样的..

另外一种加载内容的方式可以使load()方法,关于用法可以查阅api,简单说说上面的用load如何加载

代码

复制代码 代码如下:



   
   
   


   

   
   

   


   




这样就把内容加载到页面里了,有一点问题就是发现页面中返回的内容和alert弹出的有些不一样,alert弹出的返回html标签,而页面没有,那是因为页面已经解析了html代码

其他的添加,修改,删除等基本操作也是如此,大同小异,只是在doaction.aspx页面中调用不同的方法而已,下面把主要的jquery代码贴出来看看

复制代码 代码如下:

function addpinlun()
{
   var $CommentParentID    =arguments[0];
 var $CommentUser =$('#CommentUser').val();
 var $CommentText =$('#CommentText').val();
 var $CommentValidate    =$('#CommentValidate').val();

if($.trim($CommentUser)=='')
{
  alert("请填写昵称!");
  $("#CommentUser").focus();
  return false;
}
if($.trim($CommentText)=='')
{
  alert("请填写评论内容!");
  $("#CommentText").focus();
  return false;
}
if($.trim($CommentValidate)=='')
{
   alert("请输入验证码");
   $("#CommentValidate").focus();
   return false;
}
StopButton('CommentSubmit',10);
//     验证完成可以ajax添加
$.ajax({
    url: "doAction.aspx?action=add&commentparentid=" + $CommentParentID + "&commentuser=" + escape($CommentUser) + "&commenttext=" + escape($CommentText) + "&commentvalidate=" + escape($CommentValidate) + "&time=" + new Date().toString(),
    type: "GET",
    success: function (data) {
 if (arguments[0] == "ERROR") {
     alert("验证码超时,请重新输入");
 }
 else {
     getInfo();
     $("#CommentText").val("");
     //验证成功时,刷新验证码图片
     $("#CommentValidateImages").attr("src", "VerifyCode.aspx?s=" + Math.random());
     //  alert("添加成功");
     $("#alertMessgae").html(data);
 }
 $('#CommentValidate').val("");
    }
})

function StopButton()
{
    document.getElementById(arguments[0]).disabled=true;
    document.getElementById(arguments[0]).value="提交("+arguments[1]+")";
   if(arguments[1]>=1)
   {
arguments[1]--;
window.setTimeout("StopButton('"+arguments[0]+"',"+arguments[1]+")",1000);
   }
   else
   {
    document.getElementById(arguments[0]).disabled=false;
    document.getElementById(arguments[0]).value="提交";
   }
}


DoAction.aspx页面的部分代码页贴出来
复制代码 代码如下:

if(Request.QueryString["action"]!=null && Request.QueryString["action"]=="add")
 {
     if (Session["VerifyCode"].ToString().ToLower() != commentvalidate.ToLower())
     {
  Response.Write("ERROR");
     }
     else
     {
  DBQuery.ExecuteScalar("insert into comment(commentparentid,commentuser,commenttext,commentreply,commentip) values('" + commentparentid + "','" + commentuser + "','" + Server.HtmlEncode(commenttext) + "','','" + Request.ServerVariables["REMOTE_ADDR"] + "')");
  Response.Write("<script>alert('评论发表成功!</script>");
     }
 }

ajax里的属性很多,可以查看api,根据自己的需要调用不同的属性就可以了,这里面有一点需要注意的是

如果判断用户名是否有重复的时候,要使用$.getIfModified而不能是用$.get,大家可以测试一下

如果使用$.get你第一次注册了一个名字,你不要做其他的操作,你再在文本框里面输入相同的名称,那个时侯还能注册的,这点要注意。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

See all articles