) Jquery ajax usage and cross-origin access solutions

Source: Internet
Author: User

Original article address: ***/UIweb/jquery_ajax_kuayujiejue.html

In recent development, the smart phone project was designed to provide several demos for leaders. Jquery and jqeury mobile are mainly used.

Jq jqm is increasingly powerful. I sincerely admire the Development and Maintenance Team. During development, haha designed multiple platforms. The management center in charge of me needs to provide interfaces for website B to verify and return a bunch of html code. To minimize the development workload of website B, I thought of a method similar to Baidu advertising alliance and sogou Alliance's reference of js Code. Just do what you say. First, let's take a look at the practices of sogou Consortium: (why can I go there? Because I have a website for record filing. Www.360yi.net) <script type = "text/javascript">
Var sogou_ad_id = 209344;
Var sogou_ad_height = 90;
Var sogou_ad_width = 728;
</Script>
<Script language = 'javascript 'Type = 'text/JavaScript 'src = 'HTTP: // images.sohu.com/cs/jsfile/js/c.js'> </script>
We can see that two pieces of code are obvious: 1. It is a global variable, which is to confirm the website advertisement number and configuration width and height. 2. according to this idea, I need to provide an external link js file. For parameters that need to be configured, I can define global variables. (later, I made a parameter analysis, you don't need global variables ). Deep logic is hidden behind small js files. Idea: 1. after receiving the parameter data of the caller, call my js function (document ). ready is processed by default after being loaded); 2. (document ). the ready function calls the background logic code. My background is aspx, so I made an Apsx page to process this request. There is a problem here, which leads me to a detour. Javascript cannot be accessed across regions, and the historical reasons are long. What is cross-Origin

For security reasons, JavaScript does not allow cross-origin calls to objects on other pages. However, security restrictions also bring a lot of trouble to inject iframe or ajax applications. First of all, what is cross-origin is simply because of restrictions on the JavaScript same-origin policy. js under the.com domain name cannot operate on B .com or the objects under the c.a.com domain name.

Implementation: if there are any problems, we will google it (here we will talk about the search technology problem, google's strongest, baidu is floating cloud ). Find the code and run the Code. If the blogger does not provide the download, he must take the form of a mother-in-law. Alas, there is no free lunch in the world, and you have already shared your knowledge. Don't force it. Jquery implements ajax access in many ways. It also supports post and get, but only the get method can implement cross-origin access. Post Code: $. ajax ({// use the post mode com_id = 135 type: "Post", // the page where the method is located and the url of the method name :" http://localhost:3101/Image.aspx?id= "+ S_id, contentType:" application/json; charset = UTF-8 ", dataType:" json ", data:" {s_id: '"+ s_id + "'}", // here is the parameter to be passed, in the format of data: "{paraName: paraValue}". The following shows the data returned by success: function (data. d. Obtain the content var adas = data. d; $ ("# divShowtwo" ).html (adas) ;}, error: function (err) {alert (err. toString) ;}}); Implement the get method $. ajax functions are also supported. $. the getJSON function is simpler. Var AjaxUrl =" http://localhost:3101/Image.aspx?id= "+ S_id +" & jsoncallback =? "; $. GetJSON (AjaxUrl, function (Json) {$ (" # divShowtwo ").html(Json.html );});

JQuery. getJSON (url, [data], [callback]) loads JSON data across domains.

  • Url: the address where the request is sent

  • Data: (optional) key/value parameter to be sent

  • Callback: (optional) callback function for successful Loading

The supported time is the same as that of $. ajax. Note: jsoncallback =? It is a required parameter. Other parameters can be used for parameter passing through URLs. For example? ID = 23 & Name = test & background Code: The Image. aspx page must implement a resposne json segment. String jsoncallback = Request. queryString ["jsoncallback"]; Response. contentEncoding = Encoding. UTF8; Response. contentType = "application/json"; HttpContext. current. response. contentType = "text/json"; string rehtml = ""; try {StringBuilder sb = new StringBuilder (); if (id. length> 0) {string imgurl = GetPicURL (model. QRcodeURL); sb. append ("<p> www.360yi.net </p> "); Rehtml = Cleaner (sb. ToString ());} Catch (Exception ex) {rehtml = "";} Response. write (jsoncallback + "({\" html \ ": \" "+ rehtml +" \ "})"); Response. end (); Note: Server Interface page 1. string jsoncallback = Request. queryString ["jsoncallback"]; this is a required parameter. 2. The output must be jsoncallback + the output JSON string. Json is used to pass html processing: json <>/\ and other keywords MUST be escaped. You can see a function. Cleaner (). Json html Escape is implemented.  /// <Summary> /// json html string escape // </summary> /// <param name = "_ s"> </param> // <returns> </returns> public static string Cleaner (string _ s) {if (_ s = null) return ""; System. text. stringBuilder sb = new System. text. stringBuilder (_ s); sb. replace (@ "\", @ "\"); sb. replace (@ "'", @ "\'"); sb. replace (@ ", @" \ "); sb. replace (Environment. newLine, @ "\ n"); // replace \ r \ n sb. replace ("\ n", @ "\ n"); // single replacement sb. replace ("\ r", @ "\ n"); return sb. toString ();} In addition, you can look at the C # json parsing class:JSON parsing class (C #)

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.