How to make a successful JSON call from Javascript

I am very puzzled by this for a very long time. I want to get this valuable knowledge on how to call JSON correctly. Help me people.

So, I am making a call this way:

$.ajax({ type : "POST", url : "http://quote.mythicalQuotes.com/unicorn/service/historical/json?callback=callme&symbols=APPL", dataType: "text", cache : false, data : My_Array, error : function(request,error){alert(request+" "+error); }, success : function(data) { alert("Response" + data); }//success }).fail(function(textStatus, errorThrown) { alert("error Error"); console.log("The following error occured: "+ textStatus, errorThrown); }); 

But it fails and issues an error warning. Good coding!

Now paste " http://quote.mythicalQuotes.com/unicorn/service/historical/chart/lite/json?callback=callme&symbols=APPL " into the URL of my browser. JSON format:

  callme( { "SYMB" : [ { "DESCRIPTION" : "APPL, "BARS" : { "CB" :[ { "lt" : "09-01-2011::20:00:00", "op" : "16.31", "cl" : "15.22", "hi" : "16.45", "lo" : "14.72", "v" : "17768019" }, { "lt" : "09-02-2011::20:00:00", "op" : "15.22", "cl" : "14.22", "hi" : "19.45", "lo" : "10.72", "v" : "17768000" } ] } ] }) 

So what kind of crime am I doing here that provokes my anger at this particular Javascript semantics / syntax?

A few reasons why I thought it might cause this. 1. The same origin policy. 2. Invalid JSON format returned. 3. The stupidity of my code.

Please, help.

+4
source share
1 answer

This is a JSONP type response. Add dataType: jsonp to your jQuery AJAX request. Since you also explicitly specify a callback function, also add jsonpCallback: callme . See jQuery for more details (scroll down to the "dataType" section).

 $.ajax({ dataType: "jsonp", jsonpCallback: "callme", // ... success: function(data) { alert(data); // should show the JSON: { "SYMB" : ... } } }); 

You mentioned cross-domain policy; The JSONP specification is a workaround for this policy that blocks cross-domain requests. The idea is that instead of returning data, the server returns a Javascript fragment containing the data. The client then performs the returned function to retrieve the data. The jQuery ajax method has built-in functions to handle all this behind the scenes.

+6
source

Source: https://habr.com/ru/post/1441348/


All Articles