简体   繁体   中英

How to GET data from API

My API URL contains a payment transaction ID. I want to GET the data about this transaction from my API. The part that says console.log(response); is where I need to GET the data from the API. I will then fill this data into labels. How can I do this? I am using jQuery, ASP.NET, and C#. Thanks.

    $.ajax(settings).done(function(response) {
        console.log(response);
    });

Adding 'success' and 'error' methods to the ajax call will help fetch the data and error codes.

Here is a working example:

$.ajax({
    type: "GET",
    contentType: "application/json",
    url: "URL_WITH_TRANSACTION_ID",

    headers: {
              "Authorization": "auth-header-string"
            },
    success: function (output) {
        console.log("Success: " + JSON.stringify(output))
    },
    error: function (e) {
        console.log("ERROR : ", e.responseText)
    }
})

Maybe native fetch is better choice? Just suggestion.

const { transaction_id } = await fetch(settings).then(r => r.json())

Tell the $.ajax function to expect a JSON response. Do this by adding "datatype": "json" to the settings object. This now means that the response you receive will be treated as JSON , meaning if it is a string with an object in it, it will turn the string into a workable object for you.

From the jQuery documentation:

dataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

function SubmitTransaction() {

    // Card Card US Transaction Settings and Data
    var settings = {
        "url": "URL_WITH_TRANSACTION_ID",
        "method": "GET",
        "dataType": "json", // Add this line.
        "headers": {
            "X-Forte-Auth-Organization-Id": "ORGID",
            "Authorization": "AUTHID",
            "Content-Type": "application/json",
        },

    }

    $.ajax(settings).done(function(response) {
        console.log(response.transaction_id);
        console.log(response.organization_id);
        console.log(response.location_id);
        console.log(response.status);
        // etc..
    });
}

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