WEBQQ Registration and Registration page--Using JSONP cross-domain

Source: Internet
Author: User
Tags setcookie

Brief introduction:

We know that Ajax is used for data interaction, but it cannot cross domains, and cross-domain refers to a resource that requests another domain name from a Web page of one domain name. For example, from the http://www.baidu.com/page to request http://www. Google.com 's resources. The strict definition of cross-domain is that as long as the protocol, the domain name, the port has any difference, it is considered to be a cross-domain. That is, if a company's official website has been reformed, the previous website website and the new can be accessed, because the domain name has a slight change, then the company's official website can not jump to their other official website information, which is obviously very inconvenient, so jsonp on the appearance, it to solve the problem. Today I start from a project to analyze the specific use of JSONP.

WEBQQ Project:

Let's start with the layout of the sign-in page:

<div id="Login_box">User name:<input id="User"Type="text"Value="Aubagne"/> <br/><br/>Dense&nbsp; Code: <input id="Pass"Type="text"Value="123"/><br/><br/> <input id="Login"Type="Button"Value="Login"/> <input id="Reg"Type="Button"Value="Register"/> </div>

Add Style

* { margin:0; padding:0; List-style:none; font-family: "Microsoft Jas Black", "Zhang Haishan Sharp line body Jane"}body{ text-align:center;} #login_box {width:300px; padding:10px; border:1px solid #000; margin:100px auto;}

Then encapsulated good one JSON function, this function, url,data,success,error,cbkey,timeout these six parameters is optional, URL is the company gives you the PHP address, data is the user name we want, password, Avatar and so on and so on data; the Sucsess function is the function that will be called when we jsonp the request, the error is the function to be called Jsonp the request failed, the Cbkey represents the callback callback function, and the timeout is deferred, if the corresponding instruction is not completed within the specified delay time. , the server will tell the page do not wait, directly call the load error of the function bar! These parameters are sometimes used, sometimes only in parts, so we use the parameter options to represent them in order to be used.

Our code for JSONP is placed in function json (opations) {}, in which we first sort the options:

options = options| | {}; if return ; Options.data=options.data| | {};options.success=options.success| | NULL ; Options.error=options.error| | NULL ; Options.cbkey=options.cbkey| | ' CB ' ; options.timeout=options.timeout| | 0;

Here's a step-by-step write callback function

First of all, we have to prepare the necessary ingredients:

var cbvalue    =    'jsonp'+math.random ();

You know, the reason for adding math to this is to keep the function name random so that each refresh function is different.

In order to prevent the function name of this callback function from appearing. Instead of throwing an error, we replaced it with replace, just to see. just remove it.

Options.data[options.cbkey]=cbvalue.replace ('. ',');

And then we'll do the function, and we'll call it later.

window[options.data[options.cbkey]]=Function (JSON) {                clearinterval (timer);                 && options.success (JSON);            document.getElementsByTagName ('head') [0].removechild (oscript);        Window[options.data[options.cbkey]]=null;    };

This is the function that the JSONP request succeeds to call, in order to maintain the script reference after each refresh is not the same and performance optimization, we want to delete the script tag, that is, the use of the label removed, src front link, the hind legs take off, but if there is a situation in this interval, such as the middle of the network broken not hanging, So we need to remove the src when it succeeds, and then delete it after the function call.

Then to do the URL related processing:

var arr=[];  for (var in options.data) {        Arr.push (key+ ' = ' +encodeuricomponent (Options.data[key]) );    }     = options.url+ '? ' +arr.join (' & ')

Declare an empty array, then encode the string as a URI component through encodeURIComponent, put the encoded push into an empty array prepared, and finally use the array & to separate the paragraphs into strings. The point of knowledge here is data type conversion.

var oscript=document.createelement (' script ');    Oscript.src=options.url;    document.getElementsByTagName (' head ') [0].appendchild (Oscript);

This step is to create a script tag and put it into the page, the knowledge point is the DOM operation.

if (options.timeout) {        var timer=settimeout (function() {            options.error && options.error ();            Window[options.data[options.cbkey]]=function() {                       };            },options.timeout);    }        

This is the error function that is called after the delay.

At this point our JSONP function is encapsulated!!

About cookies

Here we talk about cookies, his main role is to save information, used to remember the user name when logged in, etc., two pages to transmit data,

Main features: ① cannot cross the domain,

② storage space is small, around 4k

③ a domain name has only one set of cookies

④ not safe, so don't save your privacy.

Privacy cannot be guaranteed after the ⑤ validity period

Of course, the characteristics of the cookie more than these, because this focus on the JSONP, so the author of the cookie only in this rough introduction, there is time to do more detailed research, now the packaging function about Coookie directly attached:

functionRemovecookie (name) {Setcookie (name,",-1);}functionGetCookie (name) {//alert (document.cookie);     varArr=document.cookie.split ('; ‘);  for(vari=0;i<arr.length;i++){        varArr2=arr[i].split (' = ')); if(name==arr2[0]){            returnArr2[1]; }    }    return‘‘;}functionSetcookie (name,value,timeout) {varD=NewDate (); D.setdate (D.getdate ()+timeout) Document.cookie= name+ ' = ' +value+ '; expires= ' +D; }

Let's edit this login page directly in the HTML document of our previous page layout:

First introduce the JSONP function, we put it in a jsonp.js file, and then introduce the function of the cookie, we put this cookie file name Cookie.js, the code is introduced as follows:

<src= "Cookie.js"></script><  src= "Jsonp.js"></script>

Then let's start with the core JavaScript operation.

Grab object:

var oreg=document.getelementbyid (' reg '); var ologin=document.getelementbyid (' login '); var ouser=document.getelementbyid (' user '); var opass=document.getelementbyid (' Pass ');

The following is the URL address, everyone according to the company's PHP interface link into it can be

The following is the registered editor, to achieve the desired effect is when the user name and password entered after clicking on the registration, if the user name has not been registered, the registration is successful, and then click Login, you can enter the chat interface, if the user name is registered, then the pop-up user name is ready to occupy, and then repeat the above operation, The following is a JavaScript implementation.

Registration section:

At this time to find the company to the corresponding registration part of the interface, shape such as:? a=reg&user= user name &pass= password &face= avatar id&cb=xxx

The code demonstrates the following:

oreg.onclick=function(){        //? a=reg&user= user name &pass= password &face= avatar id&cb=xxxJsonp ({url:url, data: {A:' Reg ', User:oUser.value, Pass:oPass.value, face:1+math.random () * (8-1)}, Success:function(JSON) {//{err:0, msg: "Registered successfully"}alert (json.msg); if(json.err==0) {alert (json.msg); }Else{alert (json.msg);        }            }        }); };

The code for the login section is shown below:

ologin.onclick=function(){        //? a=lgn&user= user name &pass= password &cb=xxxJsonp ({url:url, data: {A:' LGN ', User:oUser.value, Pass:oPass.value}, Success:function(JSON) {//{err:0, msg: "Login Successful", Face: Avatar ID, login_time: Last Login time, token: "token"}                if(json.err==0){                    //Jump Page                    //alert (Json.token);//{13666022-d398-d647-70e2-2c247768ef04}Setcookie (' token ', json.token,1);//Save CookiesSetcookie (' username ', ouser.value,1);//Save Cookieswindow.location.href= ' chart.html '                    }            }        }); };

At this point, the registered login page has been completed!

WEBQQ Registration and Registration page--Using JSONP cross-domain

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.