5 ways to deal with js cross domain problems
- 2020-03-30 04:30:36
- OfStack
Two days ago, I encountered a cross-domain problem, which can be solved by using jsonp. (# (link:))
Recently, I reorganized it:
1. The json.
Ajax request, dataType jsonp. This form requires the request to be adjusted on the server to return a callback([json-object]). If the server returns a normal json object. When debugging, the chrome console will report an "Uncaught SyntaxError: Unexpected token" error. "SyntaxError: missing; "Before statement" error.
2. The iframe across domains.
Add an iframe element to the page to set the SRC of the iframe to the url of the get request when a get request needs to be invoked.
var url = "http://xxx.xxx.xxx?p1=1&p2=2";
$("#iframe").attr("src", url);//Across domains, using iframe
The iframe approach is stronger than jsonp, and in addition to handling HTTP requests, it can also implement cross-domain js calls.
3. SRC attribute processing of script elements
The SRC attributes of iframe, img, style, script and other elements can directly request resources from different domains. Jsonp is a simple implementation of cross-domain request resources by using script tags. Form.
var url="http://xxx.xxx.xxx?p1=1";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
4. Use get processing on the server.
For the business does not require in the front end of the processing, you can do a encapsulation in the server side, and then the server side calls, so that the cross-domain problem can be solved. The code then USES either synchronous or asynchronous mode, depending on whether the request is sent or whether it needs to get a return value.
private static void CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
request.BeginGetResponse(null,null);//Asynchronous < br / >
//return request.GetResponse() as HttpWebResponse;
}
5. The flash across domains
Too sophisticated ==, more research
Summary: the above five methods are the common way to solve the js cross-domain problem, the last one is more high-end, I will make up for it.