Jquery +ajax+c-sharp to achieve a simple example of no refresh operation database data

  • 2020-03-30 01:38:22
  • OfStack

We know the difference between a synchronous execution and asynchronous execution, in order to better improve the user experience, we will use asynchronous way to deal with some problems, after all of the single thread synchronization may cause stuck back to wait for a phenomenon, is not very friendly, so you can use ajax to complete the user experience, we are now the way of how to use the jquery ajax to achieve no refresh obtain content

We're just getting content unilaterally, paging and so on, and we'll talk about paging without refreshing later

In the page we put a Div container to hold the returned content

< Div id = "comment" >
< Img SRC ="images/ wait.gif "title=" data loaded..." / > < / div>

Note: wait.gif is a progress bar-like effect that is displayed when unloaded content is not loaded, thus improving the user's experience. And then the most important part is the jquery part, which you do with ajax

Code:


function getInfo()
{
   $.ajax({
    url:"doAction.aspx?fig=reader&id=1&page=1",
    type:"POST",
    success:function(Data)
    {
      $("#comment").html(Data);
//$("#comment").html(arguments[0]);  
    },
    error:function()
    {
alert(" Application error ");
    }
   })
}

Url: the url pointed to

Type: the method of submission, which can be POST or GET

Success: the function that executes after successful communication

Error: a function executed after a communication failure

BeforeSend: communication before execution of hansek

Complete: the function that executes after the communication is complete

POST is used here, which is safer than Get, so it can be replaced with the following


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

It can be seen that the parameters are written in different ways. POST submission method is adopted. The difference between the first way and the second way is as follows:

First of all, when you receive parameters, in the doaction.aspx page, the first way is request-querystring [" FIG "], and the second way is request-form [" FIG "].

Secondly, in the first way, when the communication fails, the error message can be returned in a friendly way, while in the second way, it cannot be returned temporarily

Then in the doaction.aspx page, you simply do the appropriate processing


if (Request.Form["fig"] != null && Request.Form["fig"].ToString() == "reader")
 {
     ajax_getcomment("1",1);
 }
//Get the data from the database
    private void ajax_getcomment(string id, int page)
    {
 using (CommentBO cm = new CommentBO(id, page - 1))
 {
     Response.Write(cm.getCommentContent());
 }
    }

The same is true with Get ("",{},function(){}).

Another way to load content is to use the load() method. For usage, you can refer to the API

code


<!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 src="js/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
 $(function () {
     $("#btnLoad").click(function () {
  $("#content").load("doAction.aspx",{fig:"reader",id:"1",page:"1"},function (responseText, textStatus, XMLHttpRequest) {
      alert(responseText);
  });
     })
 })
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input type="button" id="btnLoad" value=" loading load" />
    <div id="content">
    </div>
    </form>
</body>
</html>

This loads the content into the page, and one of the problems is that the content returned on the page is a little different from what alert pops up. Alert pops up with an HTML tag, but the page doesn't, because the page has already parsed the HTML code

The same is true for other basic operations such as add, modify, delete, etc., but different methods are called in the doaction.aspx page


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

if($.trim($CommentUser)=='')
{
  alert(" Please fill in the nickname! ");
  $("#CommentUser").focus();
  return false;
}
if($.trim($CommentText)=='')
{
  alert(" Please fill in the comments! ");
  $("#CommentText").focus();
  return false;
}
if($.trim($CommentValidate)=='')
{
   alert(" Please enter the verification code ");
   $("#CommentValidate").focus();
   return false;
}
StopButton('CommentSubmit',10);
//        Validation is complete and can be added with 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(" Verification code timeout, please re-enter ");
 }
 else {
     getInfo();
     $("#CommentText").val("");
     //When verification succeeds, refresh the captcha picture
     $("#CommentValidateImages").attr("src", "VerifyCode.aspx?s=" + Math.random());
     //  Alert (" added successfully ");
     $("#alertMessgae").html(data);
 }
 $('#CommentValidate').val("");
    }
})
}  
function StopButton()
{
    document.getElementById(arguments[0]).disabled=true;
    document.getElementById(arguments[0]).value=" submit ("+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=" submit ";
   }
}

Part of the code page of the doaction.aspx page is posted

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(' Comment published successfully !</script>");
     }
 }

There are many attributes in ajax, you can view the API, according to their own needs to call different attributes can be, there is a point to note is that

If you need to use $.getifmodified instead of $.get to see if the username is repeated, you can test it

If you register a name for the first time with $.get, you don't do anything else, you type the same name in the text box again, you can still register that time, this should be noted.


Related articles: