How Ajax accesses data across domains
Recent problems encountered in the process of doing a project, a site needs to access the data of another site, and through scripting, and due to the limitations of the same-origin policy, the developer can no longer communicate with the external server when using XMLHttpRequest. Jsonp is a way to bypass the same-origin strategy by using JSON with the <script> tag to directly return executable JavaScript functions or JavaScript objects from the server side. Currently JSONP has become the preferred cross-domain choice for most of the company's Web applications, although JSONP is an unofficial agreement about JSONP's introduction, a lot on the web, and now begins to describe how to access data across domains.
Development environment: Visual Studio + jQuery
Front-end Code (caller):
var baseUrl = "http://localhost:59334/";
$.ajax ({
URL : BaseUrl + "account/validatecode?validatecode=" + code + "&jsoncallback=",
type: ' GET ',
dataType: ' JSON ',
success: function (data) {
console.log (data). Content);
},
error:function () {
console.log (arguments);
}
});
Backend code (callee, C #):
public string Validatecode (string validatecode)
{
String callback = request["Jsoncallback"];
String result = "";
if (session["Captchacode"]! = NULL)
{
if (session["Captchacode"]. ToString (). ToLower ()! = Validatecode.tolower ())
{
result = "0";
if (! String.IsNullOrEmpty (callback))
{
result = Callback + "({Success: ' True ', Content: ' 0 '})";
}
}
Else
{
tick = 0;
Emailvalicodeexpired = false;
result = "1";
if (! String.IsNullOrEmpty (callback))
{
result = Callback + "({Success: ' True ', Content: ' 1 '})";
}
}
}
if (String.IsNullOrEmpty (Result))
{
if (! String.IsNullOrEmpty (callback))
{
result = Callback + "({Success: ' True ', Content: ' 0 '})";
}
Else
{
result = "0";
}
}
return result;
}
The caller and callee are two Web applications;
About "jsoncallback=?", when sending Ajax requests, JQuery automatically replaces the "?" behind jsoncallback with the correct function name (callback function)
(Generally long this kind: "jquery1830798391871119546_1449898179923") to execute the callback function, so the string returned in C # should be written like this:
String result = callback + "({Success: ' True ', Content: ' 1 '})";
In fact, the return is the shape of a jquery script below:
"jquery1830798391871119546_1449898179923 ({Success: ' True ', Content: ' 1 '})"
Note the Red Word section, which is a JSON-formatted data, because the data format required to send an AJAX request is JSON
The result must not be written like this: return Json (result, jsonrequestbehavior.allowget); In this case, the callback function is serialized and cannot be executed at the end;
Common error: 1 jquery1830798391871119546_1449898179923 is not called
2 ParserError
3 Cross-origin requests have been blocked: the same-origin policy prohibits reading remote resources located in HTTP://LOCALHOST:59334/ACCOUNT/VALIDATECODE?VALIDATECODE=RUCR. (Reason: CORS header is missing ' Access-control-allow-origin ').
The first error may be because the AJAX request was sent without adding "jsoncallback=?" This sentence
If datatype write "JSONP", then the URL of the request can not take "jsoncallback=", the server side needs to use request["callback"] to get the callback function, that is, the shape of the code below:
Front-End Code:
$.ajax ({
URL : BaseUrl + "account/validatecode?validatecode=" + code,
type: ' GET ',
dataType: ' JSONP ',
success:function (data) {
Console.log (data. Content);
},
error:function () {
console.log (arguments);
}
});
Background Code (abbreviated):
String callback = request["Callback"];
String result = callback + "({Success: ' True ', Content: ' 1 '})";
return result;
General error 2 and error 11 appear, may be the result of the return {Success: ' True ', Content: ' 1 '} This part of the generation is wrong, causing the callback function can not parse JSON data;
As for error 3 is a cross-domain failure, there is a problem when sending Ajax requests, perhaps the requested URL does not add "jsoncallback=?" It may also be that datatype is not specified as "JSONP" format, note:
Add jsoncallback= in the URL and datatype as "JSONP", choose one, and if datatype is "JSONP", jquery will automatically add callback=jquery183 to the URL when sending the request. 0798391871119546_1449898179923 This sentence, above has the explanation, no longer repeat;
OK, the instructions are complete!
Ajax cross-domain access