This article mainly introduces js cross-origin principles and solutions. Cross-origin problems are caused by the same-origin policy in javascript language security restrictions. If you want to learn more about cross-origin, refer to this article.
1. What is cross-origin?
We often use ajax requests on pages to access data from other servers. In this case, the client may encounter cross-origin issues.
Cross-origin is caused by the same-origin policy in javascript language security restrictions.
To put it simply, the same-source policy means that a script can only read the properties of windows and documents from the same source. The same source here refers to the combination of host names, protocols, and port numbers.
For example:
2. Implementation Principle
In the html dom, the Script tag can access data on the server across domains. Therefore, you can specify the src attribute of the script as a cross-domain url to achieve cross-origin access.
For example:
This access method is not feasible, but the following method is acceptable.
There is a requirement for the returned data, that is, the data returned by the server cannot be simply {"Name": "zhangsan "}
If this json string is returned, we cannot reference this string. Therefore, the returned value must beVar json = {"Name": "zhangsan"}, or json ({"Name": "zhangsan "})
In order to keep the program from reporting errors, we must establishJson Functions.
3. Solution
Solution 1
Server:
protected void Page_Load(object sender, EventArgs e) { string result = "callback({\"name\":\"zhangsan\",\"date\":\"2012-12-03\"})"; Response.Clear(); Response.Write(result); Response.End(); }
Client: