cross domain ajax call
i tried to make an cross domain ajax call with native javascript and it works with out any jsonp techniques, i am wondering how it is possible . i read that cross domain ajax calls cannot be made due to security risk
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
url=document.getElementById('url_data').value;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadysta开发者_StackOverflow社区techange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<div id="myDiv"></div>
<input type"text" id="url_data" value="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20flickr.photos.info%20where%20photo_id%3D'2186714153'&format=json"/>
<button type="button" onclick="loadXMLDoc()">Request data</button>
</body>
</html>
can some one help me
The site has the Access-Control-Allow-Origin: *
response header, which allows cross-origin requests from any(*
) site.
This makes the server ignore the security risk and send the response. However, i suggest you use a script tag and callback instead of xhr to request the data, which is the standard method to requesting JSONP (ie. jQuery's $.getJSON
function). It is much more reliable.
May be these lines of code solve your problem which is for regular web service created in asp .net & call using ajax
var jsonData = [YOUR JSON PARAMETER];
$.ajax({
async: false,
type: "POST",
url: [YOUR WEB SERVICE URL],
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ json: jsonData }),
dataType: "json",
success: OnSuccess,
failure: function(err) {
alert("Error : " + err.d);
}
});
function OnSuccess(data) {
alert("Success:" + data.d);
}
You can do one thing for that just need to set Access-Control-Allow-Origin & Access-Control-Allow-Headers in CustomeHeaders your web service web.config file.
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
If you want to allow only for specific domain , you can do that with specific value of domain instead of * value
精彩评论