I encountered a cross-domain problem two days ago, and it can be solved using jsonp. (//www.VeVB.COM/article/57889.htm)
I've sorted out recently:
1.jsonp.
ajax request, dataType is jsonp. This form requires the request to be adjusted to the form that returns callback([json-object]) on the server side. If the server returns a normal json object. Then when debugging, the "Uncaught SyntaxError: Unexpected token" error will be reported on the console of the chrome browser; the "SyntaxError: missing; before statement" error will be reported on the console of the firefox browser.
2.iframe cross-domain.
Add an iframe element to the page. When you need to call the get request, set the iframe's src to the get request url to initiate the call to the get request.
The code copy is as follows:
var url = "http://xxx.xxx.xxx?p1=1&p2=2";
$("#iframe").attr("src", url);//Cross-domain, use iframe
The iframe method is stronger than jsonp. In addition to being able to handle http requests, it can also implement js calls across domains.
3. Processing of src attributes 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 using script tags. Therefore, this is essentially the same as jsonp, and it also requires the server to request the callback... form.
The code copy is as follows:
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 those who do not have any rigid requirements for processing on the front-end, they can encapsulate them on the server and then initiate calls on the server, which can solve the cross-domain problem. Then, based on whether the request is issued or the return value needs to be obtained, we will decide whether the code uses synchronous or asynchronous mode.
The code copy is as follows:
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
//return request.GetResponse() as HttpWebResponse;
}
5.Flash cross-domain
Too cutting-edge ==, study it again
Summary: The above 5 methods are common ways to solve cross-domain problems of JS. The last one is relatively high-end. Let’s make up for it after I have studied it clearly.