How to make a jsonp call to an api using jquery

前端 未结 3 1524
梦如初夏
梦如初夏 2021-01-13 15:27

I am new to programming in general and i am having trouble getting the data into my web app when i make a call to the moviedb.org api. I am using jquery and i have read all

相关标签:
3条回答
  • 2021-01-13 15:51

    This function "post" call the server

    $.post("http://api.themoviedb.org/2.1/Movie.getImages/en/json/ed7e2e092ca896037ce13d2bf11a08f1/550&callback=?", 
       function(data){ 
        //After the server code run, this code is executed with the 
        //information of the response into the parameter 'data'
        $.each(data, function(i,item){ 
        $("").attr("src", item.image).appendTo("#images");
        });
       }, 
     json");
    

    As you can see, I put the same "each" iteration function. I do not know if you're doing it correctly, because I don't execute this code. But I strongly recommend that you try execute the code into the function(data)... with an alert(...) as I show below:

    $.post("http://api.themoviedb.org/2.1/Movie.getImages/en/json/ed7e2e092ca896037ce13d2bf11a08f1/550&callback=?", 
       function(data){
        alert(data);
       }, 
    "json");
    

    With this do you really know what s "data" vale.

    I hope you have been helpful.

    0 讨论(0)
  • 2021-01-13 15:59

    First of all you have to make sure the api your calling supports jsonp (if it doesn't you will see the json but you won't be able to do anything with it).

    Second. If you don't add a callback name so you leave the ?callback=? then jquery will add a random number to the end of your url and will most likely cause a problem. It would look like this:

    http://someurl.com?callback=140989239
    

    That only hurts you. In standard jsonp you actually insert the json into a <script> tag. To do that your going to want to do something like the following:

    var headID = document.getElementsByTagName('head')[0];
    var newScript = document.createElement('script');
    newScript.type = "text/javascript";
    newScript.src = "enter your api url that you are calling here with a specified callback"
    headID.appendChild(newScript);
    
    0 讨论(0)
  • 2021-01-13 16:07

    In short, the server you're hitting doesn't seem to support JSONP, this is server-side functionality that must be present...and isn't. I also see no mention in their API docs or forums. The URL should be ?callback=? since it's the only querystring parameter, like this:

    http://api.themoviedb.org/2.1/Movie.getImages/en/json/<apikey>/550&callback=?
    

    ...but that still won't work, since the server doesn't support it. Just as an aside: Many times something with an API key isn't going to support JSONP (since the client would have the key), if the API it using the key to restrict access...others using it just for tracking may not care.

    0 讨论(0)
提交回复
热议问题