Asp.net mvc + Ajax + Extjs + nhib.pdf Ajax

Source: Internet
Author: User
Tags javascript eval
Overview:The key technology of Ajax Asynchronous JavaScript + XML is that the browser communicates with the server without refreshing the technical scope of the current page. In this article, how does Ajax request the controller? Generally, many requests such as webservice and *. ashx are mentioned. But I will share with you the request controller technology. Details: 1. Construct XMLHttpRequestMethods for constructing objects in different browsers: var xmlHttp; function createXMLHttpRequest () {if (window. activeXObject) xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP "); else if (window. XMLHttpRequest) xmlHttp = new XMLHttpRequest ();} the attribute onreadystatechange of the XMLHttpRequest object triggers this event processor when every state changes. Generally, a javascript function readystate 0 = not initialized is called, 1 = loading, 2 = loading, 3 = interaction, 4 = response of the responseText server, indicating a string of responseXML xml objects, status http status code about the status code, you can query http: // ww Export cnblogs.com/stu-acer/archive/2009/02/06/1385005.htmlstatus text the corresponding text of the http status code, OK not found, etc. Important: 200-the server returns the webpage successfully. 404-the requested webpage does not exist. 503-the server timed out. 2. Simple Test of connection code with controllerClient code: function StratReuest () {createXMLHttpRequest (); var queryUrl = "/SystemConfig/AjaxConnect? Flag = testconn "; queryUrl + =" & timeStamp = "+ new Date (). getTime (); xmlHttp. open ("POST", queryUrl, true); xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4 & xmlHttp. status = 200) {// alert ("server return:" + xmlHttp. responseText); IsSuccessful (xmlHttp. responseText) ;}} xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xmlHttp. send (null) ;}( 1), construct queryUrl, key points In:/SystemConfig/AjaxConnect? Flag = testconn, including the request's controller Method "AjaxConnect", and the parameter "flag"; (2), and then the processing if (xmlHttp. readyState = 4 & xmlHttp. status = 200) the request has been completed and the server returns to the webpage successfully. (3) xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xmlHttp. send (null); these two statements must exist; otherwise, the server cannot be requested. Function IsSuccessful (responseStr) {var messageInfo = responseStr. split ('":"') [1]; var successInfo = messageInfo. split ('","') [0]; if (successInfo = "successful") alert ("successful! "); Else alert (" failed! "+ ResponseStr. split ('":"') [2]);} server code: /// <summary> /// test the Ajax Communication Connection /// </summary> /// <returns> </returns> [AcceptVerbs (HttpVerbs. post)] public ActionResult AjaxConnect (string flag) {string strJson = ReadJsonStringFromRequestBody (Request. inputStream); SystemConfig config = new SystemConfig (); config. createDT = DateTime. parse ("2010-6-2"); config. creator = "tester"; config. fieldGroup = 0; config. fieldN Ame = "test"; config. fieldValue = "123"; config. updateDT = DateTime. parse ("2010-6-2"); config. updator = "tester"; string strData = SystemConfigSerize. serized (config); config = SystemConfigSerize. deSerizedFromJsonString (strJson); if (flag = "testconn") {MessageData data = new MessageData (); data. flag = "successful"; data. data = strData; return this. json (data);} else {MessageData data = new MessageDa Ta (); data. flag = "failer"; data. data = "test"; return this. json (data) ;}} the feature is marked as post, and then the processing result is returned. This. Json (data); If asp.net Controller has a method to generate a json string, the returned result is: flag: successful, data: test string. 3. Add records to the database using AjaxClient: function CreateAjaxRequest () {var filedNameText = document. getElementById ("FieldName"); var fieldValueText = document. getElementById ("FieldValue"); var fieldGroupText = document. getElementById ("FieldGroup"); var creatorText = document. getElementById ("Creator"); var createDTText = document. getElementById ("CreateDT"); var updatorText = document. getElementById ("Updator"); var updateDTText = docum Ent. getElementById ("UpdateDT"); var quertStr = createDTText. value; quertStr + = ","; quertStr + = creatorText. value; quertStr + = ","; quertStr + = fieldGroupText. value; quertStr + = ","; quertStr + = filedNameText. value; quertStr + = ","; quertStr + = fieldValueText. value; quertStr + = ","; quertStr + = updateDTText. value; quertStr + = ","; quertStr + = updatorText. value; createXMLHttpRequest (); var queryUrl = "/SystemConfig/AjaxCreate? StrData = "+ quertStr; queryUrl + =" & timeStamp = "+ new Date (). getTime (); xmlHttp. open ("POST", queryUrl, true); xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4 & xmlHttp. status = 200) {// alert ("server return:" + xmlHttp. responseText); IsSuccessful (xmlHttp. responseText) ;}} xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xmlHttp. send (null);} (1) the client structure is similar: "0:00:00, tester, 0, test, 123,2010-6-2 0:00:00, tester" string, then sent to the server. (2) construct quertStr, attach it to the request string, and then request the server. (3) The required send method. Server: /// <summary> /// resolution is similar to the string "0:00:00, tester, 0, test, 123,2010-6-2 0:00:00, tester, write data to the database /// </summary> /// <param name = "strData"> string </param> /// <returns> </returns> public ActionResult AjaxCreate (string strData) {try {string dataParam = Request. params. get (0 ). toString (); if (string. isNullOrEmpty (dataParam) throw new Exception ("Id is not assigned a value! "); SystemConfig config = SystemConfigSerize. deserized (dataParam); service. save (config); MessageData data = new MessageData (); data. flag = "successful"; data. data = "createInfo"; return this. json (data);} catch {MessageData data = new MessageData (); data. flag = "failer"; data. data = "createInfo"; return this. json (data) ;}}( 1) obtain the result sent by the Client: string dataParam = Request. params. get (0 ). toString (); this sentence is important. (2) Parse, call the service, and add it to the database.
4. Ajax Json test Communication ConnectionPreviously, the client sent the string to the server, but now it lists how to use the json request and the processing method on the server. Client: function StratJsonReuest () {createXMLHttpRequest (); var queryUrl = "/SystemConfig/AjaxJsonConnect? Flag = testconn "; queryUrl + =" & timeStamp = "+ new Date (). getTime (); xmlHttp. open ("POST", queryUrl, true); xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4 & xmlHttp. status = 200) {IsSuccessful (xmlHttp. responseText) ;}} xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); var systemModelObject = new SystemConfigModel ("tester", 0, "test 0 ", "Test value 1", "tester"); v Ar systemModelJson = JSON. stringify (systemModelObject); xmlHttp. send (systemModelJson);} (1) Here json2.js is used and downloaded in the http://www.JSON.org/json2.js. (2) var systemModelJson = JSON. stringify (systemModelObject); after the Json object, send it to the server using the send method: xmlHttp. send (systemModelJson); server: /// <summary> /// test the AjaxJson Communication Connection // </summary> /// <returns> </returns> [AcceptVerbs (HttpVerbs. post)] public ActionResult AjaxJsonConnect (string flag) {string strJson = ReadJsonStringFromRequestBody (Request. inputStream); SystemConfig config = new SystemConfig (); config. createDT = DateTime. parse ("2010-6-2"); config. creator = "tester"; config. fieldGroup = 0; config. fieldName = "test"; config. fieldValue = "123"; config. updateDT = DateTime. parse ("2010-6-2"); config. updator = "tester"; string strData = SystemConfigSerize. serized (config); config = SystemConfigSerize. deSerizedFromJsonString (strJson); if (flag = "testconn") {MessageData data = new MessageData (); data. flag = "successfu L "; data. data = config. toString (); return this. json (data);} else {MessageData data = new MessageData (); data. flag = "failer"; data. data = "deleteInfor"; return this. json (data) ;}} private string ReadJsonStringFromRequestBody (Stream requstStrem) {string B = string. empty; if (requstStrem = null) return B; try {long length = requstStrem. length; byte [] buffer = new byte [length]; requstStrem. read (Buffer, 0, (int) length); // string a = Encoding. ASCII. getString (buffer); string a = Encoding. UTF8.GetString (buffer); B =. toString (). trimEnd (new char ['0']);} catch (Exception exp) {throw exp;} return B;} (1) the server has obtained the json data of the request, string strJson = ReadJsonStringFromRequestBody (Request. inputStream); read the inputstream to obtain the string. When obtaining the string, string a = Encoding. UTF8.GetString (buffer); the UTF-8 encoding format is used. Otherwise, Chinese characters cannot be displayed. 5. Ajax json detailsAjax json addition and deletion are not described here. After the server returns a long string of details, the processing method of the client is added because it is multiple objects. Client: function DetailsRequest (id) {createXMLHttpRequest (); var flagTxt = document. getElementById ("flag"); if (flagTxt. value! = "Create") {var queryUrl = "/SystemConfig/AjaxJsonDetail? Id = "+ id. toString (); queryUrl + = "& timeStamp =" + new Date (). getTime (); xmlHttp. open ("POST", queryUrl, true); xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4 & xmlHttp. status = 200) {var messageInfo = xmlHttp. responseText. split ('":"') [1]; var successInfo = messageInfo. split ('","') [0]; if (successInfo = "failer") return; if (eval ('+ xmlHttp. responseText + ')')! = Null) {var obj = eval ('+ xmlHttp. responseText + '); var filedNameText = document. getElementById ("FieldName"); var fieldValueText = document. getElementById ("FieldValue"); var fieldGroupText = document. getElementById ("FieldGroup"); if (obj. fieldName! = Null) {filedNameText. value = obj. fieldName; fieldValueText. value = obj. fieldValue; fieldGroupText. value = obj. fieldGroup ;}}} xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xmlHttp. send (null) ;}} (1) the request only attaches the id value after the request string. It is used to input the id value to the server and then returns an object/SystemConfig/AjaxJsonDetail? Id = "+ id. toString () (2) if (eval ('+ xmlHttp. responseText +') after the request is processed ')')! = Null) {var obj = eval ('+ xmlHttp. responseText + '); var filedNameText = document. getElementById ("FieldName"); var fieldValueText = document. getElementById ("FieldValue"); var fieldGroupText = document. getElementById ("FieldGroup"); if (obj. fieldName! = Null) {filedNameText. value = obj. fieldName; fieldValueText. value = obj. fieldValue; fieldGroupText. value = obj. fieldGroup;} JavaScript eval method, which can be directly serialized as an object and can be passed through obj. the attribute of the FieldName access object. Server: /// <summary> /// SystemConfig details /// </summary> /// <param name = "id"> </param> /// <returns> </returns> public ActionResult AjaxJsonDetail (string id) {try {string idStr = Request. params. get (0 ). toString (); SystemConfig config = service. getById (decimal. parse (idStr); if (config = null) {MessageData data = new MessageData (); data. flag = "failer"; data. data = "no Data found! "; Return this. json (data);} else return this. json (config);} catch (Exception exp) {MessageData data = new MessageData (); data. flag = "failer"; data. data = exp. toString (); return this. json (data) ;}} (1) same Request. params. get (0 ). toString () gets the id value passed in by the client. (2) The Service is queried from the database. And then upload the json to the client. 6. Ajax queries allClient: function AllRequest () {createXMLHttpRequest (); var queryUrl = "/SystemConfig/AjaxJsonIndex? Timestape = "+ new Date (). getTime (); xmlHttp. open ("POST", queryUrl, true); xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4 & xmlHttp. status = 200) {var messageInfo = xmlHttp. responseText. split ('":"') [1]; var successInfo = messageInfo. split ('","') [0]; if (successInfo = "failer") return; if (eval ('+ xmlHttp. responseText + ')')! = Null) {var obj = eval ('+ xmlHttp. responseText + '); CreateTable (obj) ;}} xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xmlHttp. send (null);} function CreateTable (obj) {var data = new Array (); data. push ('<table border = 1> <tbody>'); data. push ('<th> FieldName </th> <th> FieldValue </th> <th> FieldGroup </th> <th> Creator </th> <th> CreateDT </th> <th> Updator </th> <th> UpdateDT </Th> <th> PkId </th> '); for (var I = 0; I <obj. length; I ++) {data. push ('<tr>'); data. push ('<td>' + obj [I]. fieldName + '</td>'); data. push ('<td>' + obj [I]. fieldValue + '</td>'); data. push ('<td>' + obj [I]. fieldGroup + '</td>'); data. push ('<td>' + obj [I]. creator + '</td>'); if (obj [I]. createDT! = Null) data. push ('<td>' + new Date (parseInt (obj [I]. createDT. substring (6, 13 ))). toLocaleDateString () + '</td>'); else data. push ('<td>' + obj [I]. createDT + '</td>'); data. push ('<td>' + obj [I]. updator + '</td>'); if (obj [I]. updateDT! = Null) data. push ('<td>' + new Date (parseInt (obj [I]. updateDT. substring (6, 13 ))). toLocaleTimeString () + '</td>'); else data. push ('<td>' + obj [I]. updateDT + '</td>'); data. push ('<td>' + obj [I]. pkId + '</td>'); data. push ('</tr>');} data. push ('</tbody> <table>'); document. getElementById ('table1 '). innerHTML = data. join ('');} (1) Can the client directly send a request/SystemConfig/AjaxJsonIndex? (2) The processing process of the client. After the Javascript eval method processes the string, it forms the object. What I am doing here is dynamically constructing a table and then displaying the client. The access to the object can be cyclically accessed because it contains multiple records. Then, you can directly access the attribute obj [I]. FieldName. Server: /// <summary> /// Json query all configuration lists /// </summary> /// <returns> </returns> public ActionResult AjaxJsonIndex () {List <SystemConfig> configList = new List <SystemConfig> (); configList = service. getAll (); if (configList! = Null | configList. count = 0) {return this. json (configList);} else {MessageData data = new MessageData (); data. flag = "failer"; data. data = "no Data found! "; Return this. Json (data );}} 7. Ajax xml requestSince Ajax is used, the request xml must always have a client: function StartXMLRequest () {createXMLHttpRequest (); var queryUrl = "/SystemConfig/AjaxXMlDetail? Id = 70 "; queryUrl + =" & timeStamp = "+ new Date (). getTime (); xmlHttp. open ("POST", queryUrl, true); xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4 & xmlHttp. status = 200) {ReadXml ()} xmlHttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xmlHttp. send (null);} function ReadXml () {var xmlDoc = xmlHttp. responseXML; var pkIdNode = xmlDoc. getElementsByTagN Ame ("PkId"); var fileNameNode = xmlDoc. getElementsByTagName ("FieldName"); var filedValueNode = xmlDoc. getElementsByTagName ("FieldValue"); var creatorNode = xmlDoc. getElementsByTagName ("Creator"); var updatorNode = xmlDoc. getElementsByTagName ("Updator"); var outString = pkIdNode [0]. text + "***" + fileNameNode [0]. text + "***" + filedValueNode [0]. text; alert (outString) ;}( 1) request, also with parameters. (2) processing result: var xmlDoc = xmlHttp. responseXML; var pkIdNode = xmlDoc. getElementsByTagName ("PkId"); xml is directly obtained through the xmlHttp. responseXML attribute. Server: public ActionResult AjaxXMlDetail (string id) {string dataParam = Request. Params. Get (0). ToString (); if (! String. isNullOrEmpty (dataParam) {SystemConfig config = service. getById (int. parse (dataParam); if (config = null) return RedirectToAction ("SystemConfigNotFound"); XMLResult result = new XMLResult (config); return result ;} else return RedirectToAction ("SystemConfigNotFound");} XMLResult can be used to serialize objects directly. After receiving the request, the server queries and returns the json object to the client. Technical points:The mainstream operation mode for Ajax requests is to refresh the page. Communication is the processing process between the client and the server. Information interaction. SummaryAjax completes server interaction through asynchronous requests.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.