Ajax and JSON

Source: Internet
Author: User
Tags format definition javascript array

Ajax is a technique for the asynchronous refresh of page layouts.

Use Ajax to send requests to the server and get the data returned by the server and update to the interface, not the entire page refresh, in the HTML page using JavaScript to create the XMLHttpRequest (XHR) object to send to the server and obtain the returned data, Use JavaScript to create a XMLHttpRequest (XHR) object in an HTML page to make a request to the server and get the returned data, which is sent by XMLHttpRequest in the page to make an HTTP request and obtain the server's return data. This will not refresh the page. XMLHttpRequest is the core object of Ajax. Local: A small part of the refresh, the other part does not refresh; Async: During a network request, the browser does not card.

XMLHttpRequest object is the basis of Ajax

XMLHttpRequest is used to exchange data with the server in the background. This means that you can update a part of a webpage without reloading the entire page.

<script type="Text/javascript">$ (function () {$ ('#btnOK'). Click (function () {varI1 = $ ('#i1'). Val (); varI2 = $ ('#i2'). Val (); varXHR = window. XMLHttpRequest?NewXMLHttpRequest ():NewActiveXObject ('Microsoft.XMLHTTP');//Create XMLHTTP objects, consider compatibility//The Open () method of the XMLHttpRequest object is "ready" to issue a POST request to the server's ADDTEST1.ASHX (get may have a caching problem), and the POST request browser must not be cached. No request has been made here. True represents an asynchronous request. Xhr.open ('POST','addtest1.ashx?i1='+ I1 +'&i2='+ I2,true); Xhr.onreadystatechange= function () {//onReadyStateChange is called whenever the ReadyState property is changed.                      if(Xhr.readystate = =4 && xhr.state==200 ) {//ReadyState = = 4 indicates that the server has returned the completed data. may have experienced 2 before (request sent, in process), 3 (part of the data in response is available, but the server has not completed a response generation)                               $('#result'). Text (Xhr.responsetext);//gets the response data in the form of a string.                         }                     Else{Aler ("Server Error"+xhr.status);                 }                 }; Xhr.send ();//send the request and do not assume that if (xmlhttp.readystate = = 4) is executed before send!!!! //when the request is made and the server returns data, it continues to execute downward, so it does not block and the interface is not jammed, which is the meaning of "A" in Ajax "Async". Try to add a sentence of Thread.Sleep (ashx);             });     }); </script>

If you need to POST data like an HTML form, use setRequestHeader () to add an HTTP header. Then specify the data you want to send in the Send () method:

Xmlhttp.open ("POST", "ajax_test.asp", true); Xmlhttp.setrequestheader ("Content-type", "application/ X-www-form-urlencoded "); Xmlhttp.send (" fname=bill&lname=gates ");

Otherwise, the server side is unable to pass the context. request["FName"] gets the value.

Encapsulate an AJAX (seanjs.js file) yourself:

function ajax (URL, onsuccess, onfail) {varXHR =NewXMLHttpRequest?NewXMLHttpRequest ():NewActiveXObject ('Microsoft XMLHTTP'); Xhr.open ('POST'Urltrue) Xhr.onreadystatechange=function (restxt) {if(Xhr.readystate = =4) {             if(Xhr.status = = $) {onsuccess (xhr.responsetext); }              Else {                 if(onfail) {Onfail (Xhr.status)}}}     }; Xhr.send (); }

See how to call:

<script type="Text/javascript">$ (function () {$ ('#username'). blur (function () {varUsername = $ ('#username'). Val (); Ajax ('checkname.ashx?username='+username, function (restxt) {//Restxt receive from                          if(restxt=='OK') {                              $("#msg"). Text ("This user name is available"); }                         Else {                             varSTRs = Restxt.split ('|'); if(strs[0]=="Error") {                                 $("#msg"). Text (strs[1]); }}, function (status) {alert ( /c1>'Error! ');             });         });     }); </script>

Jqueryajax

It is not easy to write regular Ajax code because different browsers do not have the same implementation for Ajax. This means that you have to write extra code to test your browser. However, the jquery package simplifies Ajax, with $.get, $.post, and other effects, which describe the most commonly used $.ajax (you can get a message that the request failed).

Look at an example:

<script type="Text/javascript">$ (function () {$ (function () {$.ajax ({type:"Post"Url:"jqueryajaxtest1.ashx", data: {i1:2, I2:5}, Success:function (resText) {alert (resText); }, Error:function () {alert ("Ajax Error");            }                });        });    }); </script>

Json

Json:javascript Object Notation (JavaScript object Notation).

Ajax has a de facto data transfer standard JSON when it passes through the process of assembly and parsing if it makes its own format definition.

JSON (a standard, like XML, that JSON specifies the format in which an object is saved as a string) serializes a complex object into a string, and then deserializes the string into an object that JavaScript can read in the browser side. JSON is supported in almost all languages. JSON is a standard for representing objects (JS, Java,. net) as strings.

JSON is a string form of a JavaScript object or array format, and the HTTP protocol cannot pass a JavaScript object, so it is converted to a string for transmission.

JavaScript object (key value pair) var person= {name: ' Rupeng ', age:8};

JavaScript array:var names = [' Rupeng ', ' QQ ', ' Taobao '];

JavaScript Object array:var persons = [{name: ' Rupeng ', age:8}, {name: ' QQ ', age:15}, {name: ' Taobao ', age:10}];

JavaScript Object Association:var p = {name: ' Sean ', age:18,master:{name: ' Max ', Age:3}};

JSON is the string format of objects and arrays in Javascriptjavascript:

var json= '{name: ' Sean ', age:18,master:{name: ' Max ', Age:3}} ';

So how do you take the value inside? It also has to be converted into JavaScript objects:

var " {name: ' Sean ', age:18,master:{name: ' Max ', Age:3}} " ; var js = eval ('(')'+ js.master.name );

How to convert a JSON string to a JavaScript object:

The eval () function compiles and executes any JavaScript code. This hides a potential security issue.

jquery provides Jquery.parsejson, new browsers are natively supported, unsupported references to third-party libraries Json2.js is also available.

C # will. NET object is serialized as a JSON string: JavaScriptSerializer (). Serialize (P): NET object →json string →javascript object.

JavaScriptSerializer in the System.Web.Extensions.dll. Json.NET

" Text/plain " ; string [] name = {"jackey","Sean","Tom "  New  JavaScriptSerializer (); var json=JSS. Serialize (name); context. Response.Write (JSON);

Three ways to convert a JSON string that serializes a. NET object to JavaScript on an HTML page:

Use the $.parsejson () method provided by jquery; (not recommended, trouble!) )

$.ajax ({                    type: "Post", url: "Jsontest2.ashx",                    success:function (resText) {                        var str = $.parsejson (resText);                        for (var i = 0; i < str.length; i++) {                            alert (Str[i])                        }                    },                    error:function () {                        alert ("Error"); c10/>}                });

Add dataType: "JSON",success automatically convert the JSON returned by the server to a JavaScript object

 $.ajax ({type:   " post  , url: "  jsontest2.ashx    DataType: /span> json   "  for  (var  i = 0 ; i < str.length; I                        ++
                    },                    error:function () {                        alert (" error ");}     });

Set in the server-side ashx file

Context. Response.ContentType = "Application/json";

Form serialization, Serializearray ()

If the form element is placed in a form and is set according to the HTTP standard (with name, and so on), then $ ("#form1"). Serializearray () can get a key value array and assign this value to $.ajax's Data property.

Global events:

1) Display of global loading

$ ("body"). Bind ("Ajaxsend", function () {

Show loading

}). bind ("Ajaxcomplete", function () {

Hide Loading

});

2), Ajaxerror global error handling

$ (function () {$ ("Body"). Bind ("Ajaxsend", Function () {$ ("#imgLoading"). Show (); }). bind ("Ajaxcomplete", Function () {$ ("#imgLoading"). Hide (); }). bind ("Error", function () {alert ("Request Error");            }); $("#btnOK"). Click (function () {varI1 = $ ("#i1"). Val (); varI2 = $ ("#i2"). Val (); $.ajax ({type:"Post"Url:"addtest1.ashx", data: {i1:i1, i2:i2}, Success:function (data) {$ ("#result"). text (data);            }}                });        }); });

Ajax and JSON

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.