Now its very easy to fix cross-domain issue using JSONP
JSONP allows you to make an HTTP request outside your own domain
Following example will help you :
Suppose your url returns JSON data as :
{ "gender":"Male","website":"www.google.com"}
{ "gender":"Male","website":"www.google.com"}
then just wrapped this JSON inside the callback function on server side
here we use callback function name as "functionName"
functionName({ "Gender":"Male","website":"www.google.com"})
functionName({ "Gender":"Male","website":"www.google.com"})
<script>
function functionName(result) {
alert(" Gender : "+result.gender);
}
</script>
Now its time to use JQuery, call your url using $.getJSON function,here is the example
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script>
$.getJSON("http://localhost/app/getJson?callback=?",
function(data){ }
);
function functionName(data) {
alert("Symbol: " + data.token + ", Price: " + data.price);
}
</script>
<body>
</body>
</html>
Server side changes :
You also need to change your server side code
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String jsonData = getDataAsJson(req.getParameter("symbol")); String output = "functionName(" + jsonData + ");"; resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); out.println(output); // prints: jsonp1232617941775({"Gender":"Male","website":"www.google.com"}); }
No comments:
Post a Comment