简体   繁体   中英

Consuming web service with jQuery

I am trying to run the code below but nothing happens.

I do not receive any error messages on Firefox/Chrome in developer options.

Any idea what I am doing wrong?

$(document).ready(function () {

    jQuery.support.cors = true;

    var AltCoin = "ripple";
    //var api_url = "https://api.coinmarketcap.com/v1/ticker/" + AltCoin;
    var api_url = "https://api.coinmarketcap.com/v1/ticker/";

    $.ajax({
        method: "GET",
        dataType: "jsonp",
        url: api_url,
        data: AltCoin,
        success: function(data) {
            try {                                   
                $('#coin_value').html(data);
            }
            catch (error) {
                alert('error found');                                
            }
        }
    });
});

<article class="article">
    <h1>Ripple</h1>
    <p id="coin_value">test</p>
    <p></p>
    <p><strong></strong></p>
</article>

The script is very basic.

The issue is because the API you're calling returns data in JSON format, not JSONP. They aren't interchangeable.

To fix the problem, change dataType: 'jsonp' to dataType: 'json' . Try this:

 var AltCoin = "ripple"; var api_url = "https://api.coinmarketcap.com/v1/ticker/"; $.ajax({ method: "GET", dataType: "JSON", data: AltCoin, url: api_url, success: function(data) { console.log(data); //$('#coin_value').html(data); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <article class="article"> <h1>Ripple</h1> <p id="coin_value">test</p> <p></p> <p><strong></strong></p> </article> 

You will need to loop through the resulting object in your success handler and append the data in the required format.

Also note that if you call https://api.coinmarketcap.com/v1/ticker/ripple - as you seem to intend, yet the code is not doing - then you will be blocked by CORS.

Sir please try this i think its helpful for you

 var AltCoin = "ripple"; var api_url = "https://api.coinmarketcap.com/v1/ticker/"; $.ajax({ method: "GET", dataType: "JSON", data: AltCoin, url: api_url, success: function(data) { var content=""; $.each(data[0], function(key, value ) { content+="Key :<b>"+key +"</b> Value :<b>"+value+"</b><br/>"; }); $('#coin_value').html(content); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <article class="article"> <h1>Ripple</h1> <p id="coin_value">test</p> <p></p> <p><strong></strong></p> </article> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM